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;| id | customer_id |
|---|---|
| 1 | 99 |
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 purposetext
Error: FOREIGN KEY constraint failedThe 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