The two constraints that stop a database from holding rows that cannot be true. Try to break them and watch the insert be refused.
Primary and Foreign Keys
query.sqlSQLite
-- Try each of these in turn.
-- 1. A duplicate primary key.
INSERT INTO orders (id, customer_id, total) VALUES (1, 2, 5.00);
-- 2. An order for a customer who does not exist.
-- INSERT INTO orders (id, customer_id, total) VALUES (9, 77, 5.00);
-- 3. Deleting a customer who still has orders.
-- DELETE FROM customers WHERE id = 1;
Result
Worth knowing
A primary key is two promises in one: the value is unique, and it is never NULL.
A foreign key says this column's value must already exist in another table's key column.
The database enforces both on every write. Application code that checks first still has a race; the constraint does not.
SQLite needs PRAGMA foreign_keys = ON. Most engines enforce them by default.
Overview
A primary key is a column or set of columns whose values uniquely identify each row and cannot be NULL. A table has one primary-key constraint, though it may contain several columns. A good key is stable and actually unique in the modeled data. SQLite has a historical exception: some non-integer primary-key declarations in ordinary rowid tables can accept NULL. Declare such columns NOT NULL explicitly or use a STRICT or WITHOUT ROWID table when relying on the rule.
A primary key is a column or set of columns whose values uniquely identify each row and cannot be NULL. A table has one primary-key constraint, though it may contain several columns. A good key is stable and actually unique in the modeled data. SQLite has a historical exception: some non-integer primary-key declarations in ordinary rowid tables can accept NULL. Declare such columns NOT NULL explicitly or use a STRICT or WITHOUT ROWID table when relying on the rule.
A surrogate key such as an integer ID is convenient when no natural identifier is both unique and stable. Natural keys can still be useful as UNIQUE constraints. A surrogate ID does not make other real-world uniqueness rules disappear.
A foreign key enforces a reference
A foreign key says that a value in one table must match a candidate key in another table, or be NULL if the relationship is optional.
This prevents an order from referring to a customer row that does not exist. ON DELETE and ON UPDATE actions determine what happens when the referenced row changes; choose RESTRICT, CASCADE, or SET NULL to match the domain.
In SQLite, foreign-key enforcement must be enabled for each connection with PRAGMA foreign_keys = ON unless configured otherwise. Some engines do not automatically index the child-side foreign-key column, so add an index when joins or parent updates need it.
Composite keys and design
A composite key uses more than one column when identity is only unique in combination, such as (course_id, student_id) in an enrollment table. If referencing it, the foreign key must include the same key columns. See normalization and constraints.
Optional references and uniqueness
A nullable foreign key can represent an optional relationship, but decide whether NULL means “not assigned yet” or “not applicable.” A UNIQUE constraint on a natural identifier may permit multiple NULL values in SQLite and PostgreSQL, so combine it with NOT NULL when every row must have an identifier. Composite keys can prevent duplicate pairs such as the same student enrolling twice in one course. They also enlarge foreign keys and indexes that carry the pair. Choose clarity and stability over minimizing the number of columns.
What two guarantees does declaring a primary key give you?
No two rows may share the value, and no row may leave it NULL. A row whose identity is unknown cannot be referred to at all.
Why is a surrogate integer usually preferred over an email address as a primary key?
A natural key carries meaning and meaning changes. A person changing their email would mean updating every referencing row; a meaningless integer is stable by construction.
Why does SQLite in particular need `PRAGMA foreign_keys = ON`?
The schema parses and looks correct while guaranteeing nothing, which is worse than having no constraint at all because it invites trust.
Cheat sheet
Primary and Foreign Keys
Define a primary key and a foreign key, attempt an insert that violates each, and watch the database enforce referential integrity for you.
Ashish Jangra builds and maintains VizLearn. Every module here is written and the visualisation behind it hand-built, so the numbers in a readout come from the same code that draws the picture. Corrections are genuinely welcome and get priority over everything else — if a page states something wrong, or an animation misrepresents what the algorithm does, get in touch.