Creating Tables and Constraints · Lesson 43 of 64

SQL Foreign Keys in Your Tables

What you will learn

  • How to add a foreign key with REFERENCES
  • What the database refuses once the link exists
  • How ON DELETE rules decide what happens to children
  • How to design a parent and child pair

This lesson runs on the sample database you chose in lesson 1.1 (use the Example data picker at the top). The tables you create exist only in your browser's copy of the data; Reset data removes them. Run the cells from top to bottom.

A foreign key is a column whose values must match the primary key of a row in another table (lesson 4.1; Database Fundamentals, lesson 3.1). You declare it with REFERENCES parent (column). Here is a new child table linked to a table that already exists in the sample database:

Product notes, each one pointing to a product:

CREATE TABLE lib_product_notes (
    note_id    INTEGER PRIMARY KEY,
    product_id INTEGER NOT NULL REFERENCES products (product_id),
    note       TEXT NOT NULL
);
INSERT INTO lib_product_notes (product_id, note) VALUES (1, 'Check the handle'), (2, 'Popular gift');
SELECT * FROM lib_product_notes ORDER BY note_id;
note_id  product_id  note
-------  ----------  ----------------
      1           1  Check the handle
      2           2  Popular gift
(2 rows)

Customer remarks, each one pointing to a customer:

CREATE TABLE lib_customer_remarks (
    remark_id   INTEGER PRIMARY KEY,
    customer_id INTEGER NOT NULL REFERENCES customers (customer_id),
    remark      TEXT NOT NULL
);
INSERT INTO lib_customer_remarks (customer_id, remark) VALUES (1, 'Prefers email'), (2, 'Asked for a call');
SELECT * FROM lib_customer_remarks ORDER BY remark_id;
remark_id  customer_id  remark
---------  -----------  ----------------
        1            1  Prefers email
        2            2  Asked for a call
(2 rows)

Course notes, each one pointing to a course:

CREATE TABLE lib_course_notes (
    note_id   INTEGER PRIMARY KEY,
    course_id INTEGER NOT NULL REFERENCES courses (course_id),
    note      TEXT NOT NULL
);
INSERT INTO lib_course_notes (course_id, note) VALUES (1, 'Needs a new book'), (2, 'Popular course');
SELECT * FROM lib_course_notes ORDER BY note_id;
note_id  course_id  note
-------  ---------  ----------------
      1          1  Needs a new book
      2          2  Popular course
(2 rows)

The column is NOT NULL, so every row must point to a parent. If the link is optional, leave out NOT NULL and a row may have NULL there.

2. What the database refuses

With the link in place, a child cannot point at a parent that does not exist:

INSERT INTO lib_product_notes (product_id, note) VALUES (999999, 'No such product');
IntegrityError: FOREIGN KEY constraint failed
INSERT INTO lib_customer_remarks (customer_id, remark) VALUES (999999, 'No such customer');
IntegrityError: FOREIGN KEY constraint failed
INSERT INTO lib_course_notes (course_id, note) VALUES (999999, 'No such course');
IntegrityError: FOREIGN KEY constraint failed

FOREIGN KEY constraint failed means the parent key was not found. In SQLite, foreign key checking must be switched on (PRAGMA foreign_keys = ON). The cells in these lessons switch it on for you; in your own programs you must do it for each connection, otherwise the rule is silently ignored (Database Fundamentals, lesson 3.1).

3. ON DELETE: what happens to the children

By default the database refuses to delete a parent that has children (lesson 5.3). You can choose a different behaviour with an ON DELETE rule on the foreign key. The common ones:

Rule When a parent is deleted
(none) / NO ACTION the delete is refused while children exist
RESTRICT refused at once
CASCADE the children are deleted too
SET NULL the children stay, their link becomes NULL

Try CASCADE on our own parent and child, so the sample tables are not touched:

CREATE TABLE lib_authors (author_id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE lib_titles (
    title_id  INTEGER PRIMARY KEY,
    author_id INTEGER NOT NULL REFERENCES lib_authors (author_id) ON DELETE CASCADE,
    title     TEXT NOT NULL
);
INSERT INTO lib_authors VALUES (1, 'A. Karim'), (2, 'N. Das');
INSERT INTO lib_titles (author_id, title) VALUES (1, 'Rain Songs'), (1, 'Night Train'), (2, 'River Maps');
SELECT COUNT(*) AS titles_before FROM lib_titles;
titles_before
-------------
            3
(1 row)
DELETE FROM lib_authors WHERE author_id = 1;
SELECT COUNT(*) AS titles_after FROM lib_titles;
titles_after
------------
           1
(1 row)
CREATE TABLE lib_authors (author_id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE lib_titles (
    title_id  INTEGER PRIMARY KEY,
    author_id INTEGER NOT NULL REFERENCES lib_authors (author_id) ON DELETE CASCADE,
    title     TEXT NOT NULL
);
INSERT INTO lib_authors VALUES (1, 'A. Karim'), (2, 'N. Das');
INSERT INTO lib_titles (author_id, title) VALUES (1, 'Rain Songs'), (1, 'Night Train'), (2, 'River Maps');
SELECT COUNT(*) AS titles_before FROM lib_titles;
titles_before
-------------
            3
(1 row)
DELETE FROM lib_authors WHERE author_id = 1;
SELECT COUNT(*) AS titles_after FROM lib_titles;
titles_after
------------
           1
(1 row)
CREATE TABLE lib_authors (author_id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE lib_titles (
    title_id  INTEGER PRIMARY KEY,
    author_id INTEGER NOT NULL REFERENCES lib_authors (author_id) ON DELETE CASCADE,
    title     TEXT NOT NULL
);
INSERT INTO lib_authors VALUES (1, 'A. Karim'), (2, 'N. Das');
INSERT INTO lib_titles (author_id, title) VALUES (1, 'Rain Songs'), (1, 'Night Train'), (2, 'River Maps');
SELECT COUNT(*) AS titles_before FROM lib_titles;
titles_before
-------------
            3
(1 row)
DELETE FROM lib_authors WHERE author_id = 1;
SELECT COUNT(*) AS titles_after FROM lib_titles;
titles_after
------------
           1
(1 row)

Deleting author 1 deleted that author's two titles as well. CASCADE is powerful and dangerous: one delete can remove many rows. Use it only where the children really belong to the parent (Database Fundamentals, lesson 3.5 compares the rules).

4. Designing a parent and child

When one thing "has many" of another, the many side holds the foreign key:

Relationship Parent (one) Child (many) holds
a customer has many orders customers orders.customer_id
an author has many titles lib_authors lib_titles.author_id
a course has many sections courses sections.course_id

Create the parent first, then the child that refers to it; insert parent rows before children.

5. Many-to-many: a junction table

When both sides have many, a third table holds the pairs, with a composite primary key (Database Fundamentals, lesson 3.4):

CREATE TABLE lib_readers (reader_id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE lib_reads (
    reader_id INTEGER NOT NULL REFERENCES lib_readers (reader_id),
    title_id  INTEGER NOT NULL REFERENCES lib_titles (title_id),
    PRIMARY KEY (reader_id, title_id)
);
INSERT INTO lib_readers VALUES (1, 'Rina'), (2, 'Sam');
INSERT INTO lib_reads VALUES (1, 3), (2, 3);
SELECT r.name, t.title FROM lib_reads AS x JOIN lib_readers AS r ON r.reader_id = x.reader_id
JOIN lib_titles AS t ON t.title_id = x.title_id ORDER BY r.name;
name  title
----  ----------
Rina  River Maps
Sam   River Maps
(2 rows)
CREATE TABLE lib_readers (reader_id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE lib_reads (
    reader_id INTEGER NOT NULL REFERENCES lib_readers (reader_id),
    title_id  INTEGER NOT NULL REFERENCES lib_titles (title_id),
    PRIMARY KEY (reader_id, title_id)
);
INSERT INTO lib_readers VALUES (1, 'Rina'), (2, 'Sam');
INSERT INTO lib_reads VALUES (1, 3), (2, 3);
SELECT r.name, t.title FROM lib_reads AS x JOIN lib_readers AS r ON r.reader_id = x.reader_id
JOIN lib_titles AS t ON t.title_id = x.title_id ORDER BY r.name;
name  title
----  ----------
Rina  River Maps
Sam   River Maps
(2 rows)
CREATE TABLE lib_readers (reader_id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE lib_reads (
    reader_id INTEGER NOT NULL REFERENCES lib_readers (reader_id),
    title_id  INTEGER NOT NULL REFERENCES lib_titles (title_id),
    PRIMARY KEY (reader_id, title_id)
);
INSERT INTO lib_readers VALUES (1, 'Rina'), (2, 'Sam');
INSERT INTO lib_reads VALUES (1, 3), (2, 3);
SELECT r.name, t.title FROM lib_reads AS x JOIN lib_readers AS r ON r.reader_id = x.reader_id
JOIN lib_titles AS t ON t.title_id = x.title_id ORDER BY r.name;
name  title
----  ----------
Rina  River Maps
Sam   River Maps
(2 rows)

Worked example: add a link to a design

"Every review belongs to one product and one customer."

Step Do
1 which tables are the parents? products, customers
2 the child is reviews and holds both keys
3 product_id INTEGER NOT NULL REFERENCES products (product_id)
4 customer_id INTEGER NOT NULL REFERENCES customers (customer_id)
5 add a rule for the parent's delete if you do not want the default

The Shop sample's reviews table is built exactly like this. The tables are from the sample.

Common mistakes

  • Forgetting PRAGMA foreign_keys = ON in your own SQLite programs.
  • Referencing a column that is not a primary key or unique.
  • Creating the child before the parent.
  • CASCADE everywhere, deleting far more than intended.
  • A NOT NULL link that should be optional.

Key takeaways

  • column ... REFERENCES parent (key) makes a foreign key; the "many" side holds it.
  • The database refuses a child that points at a missing parent.
  • ON DELETE CASCADE, SET NULL or the default refusal decide what happens to the children.
  • Many-to-many needs a junction table with a composite key.

Practice

1. Write the column that links orders to customers.

Show answer

customer_id INTEGER NOT NULL REFERENCES customers (customer_id)

2. Which table holds the foreign key in "one author, many titles"?

Show answer

The titles table, the "many" side.

3. What does ON DELETE CASCADE do?

Show answer

Deleting a parent also deletes its children.

4. Why must you switch on foreign keys in your own SQLite programs?

Show answer

SQLite does not check them by default, so without it the rule is ignored.

5. What do you create for a many-to-many relationship?

Show answer

A junction table holding the two keys, with a composite primary key.

6. Which table do you create first, the parent or the child?

Show answer

The parent, because the child refers to it.