Pcornel
Browse topics
Options
Recent
Favorites
Databases · Technical reference

Primary and Foreign Keys

Direct answer

A primary key uniquely identifies each row; a foreign key references a primary key in another table so the database enforces relationships.

When to use this

Use it when designing tables or when orphaned or duplicate rows appear.

First 30 seconds

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.

Operational verification

row inserted → PK unique check → FK checked against parent

Context & applicabilityCommon mistakes · platform/version boundaries
Platform / version applicability
MariaDB / MySQL / PostgreSQL / Microsoft SQL Server concepts
applies
Structured applicability is explicit Topic metadata; it does not infer compatibility beyond the stored rows.
At a glance

Operational reference

Fast context before you go deeper.

PlatformMariaDB / MySQL / PostgreSQL / Microsoft SQL Server concepts
Scope / prerequisiteUse it when designing tables or when orphaned or duplicate rows appear.
What next?2 suggested next steps
Evidence0
On this pageJump to a specific section
Operational workflow

Verification & Troubleshooting

Start with the observed symptom, prove the nearest boundary, and move outward only when the current state is understood.

2 steps Observe → verify → isolate → change minimally → repeat the original test.
ObservedRecord what the original test actually shows

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.

Key points

Index foreign key columns (MySQL does automatically, PostgreSQL does not). Choose ON DELETE behaviour deliberately (RESTRICT vs CASCADE).

Key checks
  • SELECT … LEFT JOIN parent … WHERE parent.id IS NULL — first check for this topic
  • psql -c "SELECT now(), version();" — PostgreSQL reachable and version
  • mysql -e "SELECT NOW(), VERSION();" — MariaDB/MySQL reachable and version
  • sqlcmd -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 DELETEDeleting a parent row…
NO ACTION / RESTRICT (default)Fails while children exist
CASCADEDeletes the children too (and their children)
SET NULLSets the foreign key column to NULL
SET DEFAULTSets 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.

Source basisSource attribution states what this section is based on; it is not independent proof that the current environment matches it.

Common mistakes

  • Foreign keys without indexes.
Additional reference context Scope · expected state · examples · history · terminology Open only when you need the supporting context
Terminology layer

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.

Aliases that resolve here
primary and foreign keysprimary key foreign keyreferential integrity
Confirmation

Confirm action

Continue?