Use it when designing tables or when orphaned or duplicate rows appear.
Primary and Foreign Keys
A primary key uniquely identifies each row; a foreign key references a primary key in another table so the database enforces relationships.
1. Primary key on each table.
2. Foreign keys defined?
3. FK columns indexed (PG).
4. Orphans: SELECT … LEFT JOIN parent … WHERE parent.id IS NULL.
5. ON DELETE behaviour.
row inserted → PK unique check → FK checked against parent
Context & applicabilityCommon mistakes · platform/version boundaries
Operational reference
Fast context before you go deeper.
Verification & Troubleshooting
Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.
Use the operational verification above to establish the expected state.
Capture the concrete output, symptom, packet, log or counter before changing anything.
Step 1 How to verify Verify boundary
Insert a child with a missing parent in a test and confirm it fails. Delete a parent and confirm children follow the intended rule.
Step 2 Common failures Narrow the fault
ON DELETE CASCADE can remove large amounts of data unexpectedly. Missing foreign keys let orphaned rows accumulate. Using mutable values such as email as primary key causes painful updates.
Index foreign key columns (MySQL does automatically, PostgreSQL does not). Choose ON DELETE behaviour deliberately (RESTRICT vs CASCADE).
SELECT … LEFT JOIN parent … WHERE parent.id IS NULL— first check for this topicpsql -c "SELECT now(), version();"— PostgreSQL reachable and versionmysql -e "SELECT NOW(), VERSION();"— MariaDB/MySQL reachable and versionsqlcmd -S <server> -Q "SELECT @@VERSION"— SQL Server reachable and version
ReferenceWhat it is1 section · depth on demand
How it works
The database checks constraints on every insert, update and delete. Deferred constraints (PostgreSQL) are checked at commit instead. Surrogate keys (identity columns) are stable; natural keys can change.
ReferenceImportant terms & boundaries3 sections · depth on demand
Examples
CREATE TABLE customers (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email text NOT NULL UNIQUE
);
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id bigint NOT NULL REFERENCES customers(id) ON DELETE RESTRICT
);
CREATE INDEX ON orders (customer_id);
Documented example, not captured output. PostgreSQL does not index foreign key columns automatically — add indexes to avoid slow deletes and joins. Surrogate keys (identity/UUID) avoid changing primary keys when business data changes.
In depth
Referential actions
ON DELETE | Deleting a parent row… |
|---|---|
NO ACTION / RESTRICT (default) | Fails while children exist |
CASCADE | Deletes the children too (and their children) |
SET NULL | Sets the foreign key column to NULL |
SET DEFAULT | Sets it to the column default |
Use CASCADE only for true parts of the parent (order lines of an order), never for references to shared data (customers of orders).
Index the referencing column
PostgreSQL does not create an index on the foreign key column. Without one, every delete or key update on the parent scans the child table and takes stronger locks than necessary. MySQL InnoDB creates the index automatically if none exists.
-- PostgreSQL: foreign keys without a supporting index
SELECT c.conrelid::regclass AS child, a.attname AS column
FROM pg_constraint c
JOIN pg_attribute a ON a.attrelid = c.conrelid AND a.attnum = c.conkey[1]
WHERE c.contype = 'f'
AND NOT EXISTS (SELECT 1 FROM pg_index i
WHERE i.indrelid = c.conrelid AND i.indkey[0] = c.conkey[1]);
Adding a constraint to a big table without a long lock (PostgreSQL)
ALTER TABLE orders ADD CONSTRAINT orders_customer_fk
FOREIGN KEY (customer_id) REFERENCES customers(id) NOT VALID; -- fast, checks new rows
ALTER TABLE orders VALIDATE CONSTRAINT orders_customer_fk; -- scans, weaker lock
Key choice
Surrogate keys (bigint identity, or UUID — preferably time-ordered UUIDv7 for index locality) stay stable; natural values such as email change and then cascade through every referencing table. Keep natural values unique with a UNIQUE constraint instead.
Common mistakes
- Foreign keys without indexes.
Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Terms & aliases
Hover a linked term for a quick definition; click it to open its glossary entry. Aliases are other names that find this Topic in search.