Skip to main content

Foreign Keys

Foreign keys enforce referential integrity.

They ensure child rows reference valid parent rows.

Core Concepts

flowchart LR
A[Insert child row] --> B{Parent key exists?}
B -->|Yes| C[Accept insert]
B -->|No| D[Reject insert]
ConceptExample
Parent keycustomers.customer_id
Child referenceorders.customer_id
FK clauseFOREIGN KEY (customer_id) REFERENCES customers(customer_id)
-- Enable foreign key enforcement for this connection.
PRAGMA foreign_keys = ON;

-- Verify current setting.
PRAGMA foreign_keys;
foreign_keys
1

Code Examples

-- Valid insert sequence: parent first, then child.
INSERT INTO customers_fk (customer_id, name)
VALUES (1, 'Ada');

INSERT INTO orders_fk (order_id, customer_id, total)
VALUES (1001, 1, 59.00);
Expected output
Both inserts succeed.
-- Invalid child reference (if foreign_keys=ON).
INSERT INTO orders_fk (order_id, customer_id, total)
VALUES (1002, 999, 10.00);
Expected output
Error: foreign key constraint failed.

SQLite-Specific Nuances

SQLite Nuance

In SQLite, foreign key enforcement is connection-specific and controlled by PRAGMA foreign_keys.

Set it to ON in every application connection unless you have a deliberate reason not to.

Common Pitfalls / Best Practices

Pitfall

Declaring foreign keys in schema but forgetting to enable enforcement, leading to orphaned rows.

Best Practice

As part of app startup, execute PRAGMA foreign_keys = ON; and verify with PRAGMA foreign_keys; in tests.

Quick Challenge

Write SQL to enable foreign key checks and confirm they are active.

View Solution
PRAGMA foreign_keys = ON;
PRAGMA foreign_keys;
foreign_keys
1