← Back to SQL, page 9

sql-0176 · Easy fresher

What does a foreign key enforce, and why might SQLite not enforce it by default?

A foreign key requires that every non-NULL value in the child column exists in the referenced parent key, and it controls what happens when a parent row is deleted or updated. SQLite enforces foreign keys only when PRAGMA foreign_keys = ON is set for each connection, for backward compatibility. PostgreSQL always enforces them.

Full answer

With enforcement off (SQLite's default), an order can point at a customer that does not exist:

sql
CREATE TABLE customers (id INTEGER PRIMARY KEY);
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER REFERENCES customers(id));
INSERT INTO orders VALUES (1, 99);
SELECT id, customer_id FROM orders;
idcustomer_id
199

With the pragma on, the same insert fails:

sql
PRAGMA foreign_keys = ON;
CREATE TABLE customers2 (id INTEGER PRIMARY KEY);
CREATE TABLE orders2 (id INTEGER PRIMARY KEY, customer_id INTEGER REFERENCES customers2(id));
INSERT INTO orders2 VALUES (1, 99);
-- error on purpose
text
Error: FOREIGN KEY constraint failed

The pragma is per connection and is not stored in the database file, so every application connection must set it. A NULL foreign key value is always allowed; add NOT NULL if the relationship is mandatory.

The referenced columns must be a primary key or have a unique constraint. Index the child column too: neither engine does it automatically, and deletes on the parent need it to find child rows quickly.

sql
CREATE TABLE customers (id INTEGER PRIMARY KEY);
CREATE TABLE orders (id INTEGER PRIMARY KEY, customer_id INTEGER REFERENCES customers(id));
INSERT INTO orders VALUES (1, 99);
SELECT id, customer_id FROM orders;

-- error on purpose
PRAGMA foreign_keys = ON;
CREATE TABLE customers2 (id INTEGER PRIMARY KEY);
CREATE TABLE orders2 (id INTEGER PRIMARY KEY, customer_id INTEGER REFERENCES customers2(id));
INSERT INTO orders2 VALUES (1, 99);

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • Foreign keys require child values to exist in the parent
  • NULL child values are allowed unless NOT NULL is added
  • SQLite needs PRAGMA foreign_keys = ON per connection
  • Index the child column yourself

Common mistakes

  • Assuming SQLite enforces foreign keys by default
  • Forgetting the index on the referencing column

Follow-ups

  • What do ON DELETE CASCADE and SET NULL do?
  • How do you find orphaned rows created before enforcement was on?

Tips

  • State the SQLite pragma explicitly