Primary and Foreign Keys: A Practical Guide
Learn the difference between natural and surrogate keys, how foreign keys enforce referential integrity, cascade rules, and best practices for constraint naming.
Primary keys give rows a stable identity when the table and workload need one; natural, composite, staging, and append-only designs have different tradeoffs. Foreign keys prevent orphaned references, while delete actions, migration locks, and index behavior depend on the database engine. Learn how to validate existing data and test both rejected orphans and planned deletes.
Primary and Foreign Keys: A Practical Guide
Primary and foreign keys are how relational databases establish relationships and enforce data integrity. They shape query performance and schema maintainability. Getting them right from the start avoids pain later. This covers primary keys, foreign keys, the choices around natural versus surrogate keys, and the cascade rules that govern delete and update behavior.
Primary Keys
A primary key uniquely identifies each row in a table. Its values must be unique and non-NULL. For transactional tables that are updated, referenced, or addressed by row, a primary key is usually a sound default. It is a design choice rather than a universal rule: staging tables may omit one while data is being loaded and deduplicated, and append-only event tables may use a natural or composite uniqueness rule when that fits the event model. Add a key once the table’s identity and duplicate-handling rules are clear.
Natural Keys
A natural key is a value that exists in the real world and uniquely identifies the entity. An email address might serve as a natural key for a users table. A Social Security Number for a taxpayers table. The value has meaning outside the database.
Natural keys make sense when the real-world identifier is stable and guaranteed unique. Email addresses change when people switch jobs. SSNs have edge cases (recent immigrants, elderly who never filed). In practice, natural keys are often problematic because real-world identifiers change more than you expect.
Natural keys can also fit append-only records when the source provides a stable event identifier. A composite unique key such as (source_name, source_event_id) can make ingestion idempotent without adding an artificial primary key, though a surrogate key may still help if other tables need to reference individual events. Check the source’s uniqueness and correction behavior before treating that key as permanent.
For integrations, an external identifier such as an ISBN, SKU, or country code can be a key when it is genuinely stable, unique, and non-NULL. A common alternative is a surrogate primary key plus a unique constraint on the business identifier. That keeps internal references compact while preserving the external identifier’s uniqueness.
The failure mode is treating a natural key as immutable when it is not. ISBN-10 and ISBN-13 illustrate how an identifier format can change while older systems still rely on the original value. Natural keys that cross system boundaries are external contracts. Treat them like APIs: support a transition period, update consumers deliberately, and consider a surrogate key internally even when the natural key feels stable.
Surrogate Keys
A surrogate key has no meaning outside the database. It exists solely to identify rows. An auto-incrementing integer or a UUID serves as a surrogate key. The database generates it, and nothing in your application cares what the value is, as long as it is unique.
Surrogate keys are a practical default for many transactional tables. They have no business meaning and are usually treated as immutable after assignment, though a database does not make them immutable automatically. A primary key constraint prevents duplicates and NULLs; application permissions or additional rules are needed if updates must be prohibited.
CREATE TABLE users (
user_id INT PRIMARY KEY AUTO_INCREMENT,
email VARCHAR(255) NOT NULL UNIQUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Composite Keys
A composite key uses multiple columns to uniquely identify a row. The combination of columns is unique, but individual columns may repeat.
CREATE TABLE course_enrollments (
student_id INT,
course_id INT,
enrollment_date DATE,
PRIMARY KEY (student_id, course_id)
);
Composite keys work for junction tables in many-to-many relationships and for append-only data whose source identity is naturally a combination of fields. The primary key above combines student and course, ensuring a student cannot enroll in the same course twice.
Composite keys have tradeoffs. They make foreign key references verbose. A reference to course_enrollments requires both columns. This complexity adds up in large schemas.
Cascade Delete Flow
flowchart TD
subgraph customers["customers table"]
C1["customer_id = 1"]
end
subgraph orders["orders table"]
O1["customer_id = 1\norder_id = 100"]
O2["customer_id = 1\norder_id = 101"]
end
subgraph order_items["order_items table"]
OI1["order_id = 100\nproduct_id = 5"]
OI2["order_id = 101\nproduct_id = 7"]
end
C1 -->|ON DELETE CASCADE| O1
C1 -->|ON DELETE CASCADE| O2
O1 -->|ON DELETE CASCADE| OI1
O2 -->|ON DELETE CASCADE| OI2
With CASCADE, deleting a customer can delete matching orders and their dependent order items. Without it, the database applies the constraint’s configured action; it should reject a delete that would leave invalid references rather than leave orphans.
Foreign Keys
A foreign key establishes a link between two tables. The child column references a primary or unique key in the parent. This relationship enforces referential integrity: a non-NULL child value must match a referenced value. The examples in this section use MySQL 8.4 with InnoDB; syntax, defaults, and behavior can differ across engines.
CREATE TABLE orders (
order_id INT PRIMARY KEY AUTO_INCREMENT,
customer_id INT NOT NULL,
order_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT fk_orders_customer FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
ON DELETE RESTRICT ON UPDATE RESTRICT
);
The foreign key constraint prevents orphaned orders. If you try to insert an order with a customer_id that does not exist in the customers table, the database rejects it.
Foreign keys have a cost. Every insert and update must check the referenced table. For high-throughput write paths, this overhead accumulates. Some architectures defer integrity checks to the application layer. This trades safety for speed, and it works when your application enforces the rules correctly.
Referential Integrity and Cascade Rules
What happens when you delete a customer who has orders? The foreign key’s delete action decides. State the action in the schema rather than relying on an engine default.
ON DELETE
Cascade rules determine what happens to child rows when their parent is deleted. Picture a customers table with an orders table referencing it via customer_id. When you delete a customer row, the database needs instructions for the related order rows.
-
CASCADE: Delete the referencing rows when the referenced row is deleted. Delete a customer and all their orders disappear.
Use CASCADE when the child rows genuinely cannot exist without the parent. An order without a customer is meaningless data. CASCADE keeps your database clean automatically.
-
SET NULL: Set the foreign key to NULL when the referenced row is deleted. Delete a customer and their orders remain, but customer_id becomes NULL.
Use SET NULL when the relationship is optional and the child rows must survive the parent’s deletion. A
support_ticketstable where tickets can exist independently of thecustomerstable they reference is a good fit — the ticket stays but is now unattributed. -
RESTRICT: Reject the deletion if referencing rows exist. You cannot delete a customer who has orders.
Use RESTRICT when child rows must be reviewed or handled before a parent can be removed. A deletion request needs its own data inventory and retention decision; the foreign-key action alone does not decide what should be erased, retained, or anonymized.
-
NO ACTION: The default action in PostgreSQL and MySQL, but its timing differs. In PostgreSQL, a non-deferrable NO ACTION check is made at statement end; a deferrable constraint can be checked later in the transaction. RESTRICT cannot be deferred. In MySQL InnoDB, NO ACTION is equivalent to an immediate RESTRICT check.
Choose and declare the behavior for the database you run. Do not assume the same timing or supported actions across engines.
CREATE TABLE orders (
order_id INT PRIMARY KEY AUTO_INCREMENT,
customer_id INT,
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
ON DELETE CASCADE
);
For parent rows that must not disappear while children remain, RESTRICT is a clear choice. CASCADE can be appropriate when child rows have no independent meaning, but review the full dependency path and test the affected row counts before using it on a large dataset.
ON UPDATE
UPDATE behaves the same way. CASCADE propagates primary key changes to foreign keys. SET NULL clears them. RESTRICT and NO ACTION block the update.
In practice, primary keys rarely change once assigned, especially surrogate keys. ON UPDATE CASCADE matters more for natural keys where the business identifier might legitimately change.
ON UPDATE CASCADE makes sense for domain identifiers that actually change. Country codes shifting from ISO 3166-1 alpha-2 to alpha-3 is the classic example. Product SKUs get reformatted after a rebrand is another. In these situations, propagating the parent update to every foreign key reference is exactly what you want. Without CASCADE, either the update fails or you end up with orphaned references that your application has to clean up later.
RESTRICT and NO ACTION both prevent updates that would leave dangling references. In PostgreSQL, RESTRICT is checked immediately; a non-deferrable NO ACTION constraint is checked at statement end, and a constraint declared DEFERRABLE can be checked later in the transaction. In MySQL InnoDB, NO ACTION is an immediate RESTRICT check. Choose based on the engine and whether the transaction actually needs deferred checking.
CREATE TABLE order_items (
item_id INT PRIMARY KEY AUTO_INCREMENT,
order_id INT NOT NULL,
product_id VARCHAR(50) NOT NULL,
quantity INT DEFAULT 1,
FOREIGN KEY (order_id) REFERENCES orders(order_id)
ON DELETE CASCADE
ON UPDATE RESTRICT
);
Use ON UPDATE CASCADE only when parent-key changes are an intended domain operation and every referencing row should follow. Surrogate keys are usually kept stable by convention; a schema can still permit an update unless other rules prevent it.
Constraint Naming
Give your constraints explicit names rather than letting the database generate cryptic identifiers.
-- Bad: constraint name is database-generated like "fk_orders_customer_id"
FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
-- Good: name the constraint in the table definition
CONSTRAINT fk_orders_customer_id FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
Explicit names make debugging easier. When a constraint violation occurs, the error message includes your name, not some auto-generated hash. This matters in production where you are parsing logs, not clicking through a GUI.
Naming conventions vary. Pick one and apply it consistently. A common pattern: fk_<table>_<referenced_table> for foreign keys, pk_<table> for primary keys, uq_<table>_<column> for unique constraints.
Indexes and Keys
Primary keys are backed by a unique index, but whether that index controls physical row organization depends on the engine. InnoDB stores rows in the primary-key index; PostgreSQL does not automatically cluster table rows by its primary key. Foreign-key index behavior also varies: PostgreSQL does not create the child-side index automatically, while InnoDB may create one when needed. Check your engine and index actual join/delete patterns.
CREATE TABLE orders (
order_id INT PRIMARY KEY,
customer_id INT,
CONSTRAINT fk_orders_customer_id FOREIGN KEY (customer_id) REFERENCES customers(customer_id)
);
-- You typically want this index for query performance
CREATE INDEX idx_orders_customer_id ON orders(customer_id);
Without an index on orders.customer_id, a join may use a sequential scan, but it does not have to: the planner chooses a plan based on the database engine, table size, statistics, selectivity, and query. The child-side index can also help the database find referencing rows when a parent key is changed or deleted. Check EXPLAIN for the queries you run and test parent-side operations with representative data before adding an index.
Safely add keys to an existing table
This example is scoped to PostgreSQL 19 and a populated customers table that does not yet have a primary key. First inspect the actual production-sized data and agree how to repair duplicate or missing identifiers. A staging table can remain temporarily unkeyed during ingestion, but deduplicate and validate it before promoting it to a relational table.
-- Check for missing and duplicate parent identifiers.
SELECT COUNT(*) AS null_ids
FROM customers
WHERE customer_id IS NULL;
SELECT customer_id, COUNT(*) AS copies
FROM customers
GROUP BY customer_id
HAVING COUNT(*) > 1;
-- Add a validated NOT NULL check without an initial table scan,
-- then validate existing rows in a separate operation.
ALTER TABLE customers
ADD CONSTRAINT customers_customer_id_nn
CHECK (customer_id IS NOT NULL) NOT VALID;
ALTER TABLE customers
VALIDATE CONSTRAINT customers_customer_id_nn;
ALTER TABLE customers
ALTER COLUMN customer_id SET NOT NULL;
-- Run outside a transaction block. If duplicate writes race this build,
-- it can fail; repair the data and retry.
CREATE UNIQUE INDEX CONCURRENTLY customers_customer_id_uq_idx
ON customers (customer_id);
ALTER TABLE customers
ADD CONSTRAINT customers_pkey
PRIMARY KEY USING INDEX customers_customer_id_uq_idx;
ALTER TABLE customers
DROP CONSTRAINT customers_customer_id_nn;
For a child table, check both missing values (if the relationship is mandatory) and orphan references before adding the foreign key:
SELECT COUNT(*) AS null_customer_ids
FROM orders
WHERE customer_id IS NULL;
SELECT o.customer_id, COUNT(*) AS orphan_orders
FROM orders AS o
LEFT JOIN customers AS c ON c.customer_id = o.customer_id
WHERE o.customer_id IS NOT NULL AND c.customer_id IS NULL
GROUP BY o.customer_id;
CREATE INDEX CONCURRENTLY orders_customer_id_idx ON orders (customer_id);
ALTER TABLE orders
ADD CONSTRAINT orders_customer_id_fkey
FOREIGN KEY (customer_id) REFERENCES customers (customer_id)
ON DELETE RESTRICT NOT VALID;
ALTER TABLE orders
VALIDATE CONSTRAINT orders_customer_id_fkey;
If the relationship is mandatory, require the null check to return zero and apply the same validated-check, SET NOT NULL, and helper-check cleanup steps to orders.customer_id. If it is optional, keep the column nullable and leave those rows out of the orphan test.
NOT VALID skips the initial foreign-key scan but enforces the constraint for new or changed rows; VALIDATE CONSTRAINT checks existing rows. In PostgreSQL 19, adding a foreign key takes SHARE ROW EXCLUSIVE locks on both tables. Validation takes SHARE UPDATE EXCLUSIVE on the child and ROW SHARE on the referenced table. Setting a column NOT NULL, attaching the primary key, and removing the helper check are separate ALTER TABLE operations that generally need an ACCESS EXCLUSIVE lock; the validated check lets PostgreSQL avoid rescanning the table for SET NOT NULL. Other work can contend for these locks, and the index build and validation still use I/O. Use a production-sized rehearsal, set a lock timeout that fits your rollout policy, watch lock waits and replication lag, and be prepared to retry a metadata step if it cannot acquire its lock promptly. If validation finds rows that raced with the earlier preflight query, repair them and validate again. An online or concurrent operation is not a promise of zero impact. See the PostgreSQL 19 ALTER TABLE documentation for the lock and validation details.
This sequence is PostgreSQL-specific. MySQL 8.4 InnoDB offers different ALTER TABLE algorithms and lock options; INSTANT, INPLACE, and COPY have different limits, and an operation’s metadata lock can still matter. Check the exact operation in the MySQL 8.4 ALTER TABLE documentation before applying it. MySQL’s foreign-key documentation also describes its action defaults and supported clauses.
Integration checks: orphan prevention and intentional deletes
Run these checks against a disposable integration database with fixture IDs reserved for the test. The first insert should fail with PostgreSQL SQLSTATE 23503 because no parent exists:
-- Expected: foreign_key_violation (SQLSTATE 23503)
INSERT INTO orders (order_id, customer_id) VALUES (900002, 900001);
With a fixture customer and at least one fixture order present, a parent delete under ON DELETE RESTRICT should fail. A deliberate removal can delete the dependent records first, then the parent, in one transaction; check the affected rows and the post-conditions in the test:
-- Expected: foreign_key_violation (SQLSTATE 23503)
DELETE FROM customers WHERE customer_id = 900001;
-- After asserting that RESTRICT blocked the parent delete, clean up intentionally:
BEGIN;
DELETE FROM orders WHERE customer_id = 900001;
DELETE FROM customers WHERE customer_id = 900001;
COMMIT;
-- Assert both queries return no rows for the fixture customer.
SELECT * FROM orders WHERE customer_id = 900001;
SELECT * FROM customers WHERE customer_id = 900001;
If orders must be preserved for history or legal retention, deletion is the wrong test outcome: use the system’s approved archive, anonymization, or soft-delete process and keep the reference rules consistent with that decision.
Capacity Estimation: Foreign Key Index Storage
Foreign keys need indexes, and those indexes have storage and write costs. Here is how to size them.
Storage for a FK index is straightforward. A B-tree index on an INTEGER column consumes roughly 2–4 bytes per entry for the index itself, plus overhead for the index structure. For an orders table with 100 million rows and a customer_id FK, the index on customer_id is roughly 200–400 MB. A UUID FK (16 bytes) doubles that to 400–800 MB.
Write overhead is the more important factor. Every INSERT to the child table must also update the FK index on that column. Every UPDATE to the FK column updates the index. Every DELETE from the parent table that cascades must update the child’s FK index. If you have high-frequency writes and cascade deletes on large tables, the FK index write amplification adds up.
Estimate FK write cost: if you insert 10,000 orders per second and each has a customer_id FK, you are doing 10,000 index inserts per second to the FK index. On a busy write path, that index might become a bottleneck. Profile the actual write throughput before assuming it is free.
Rule of thumb: index FK columns when you routinely join on them in queries. Skip the index when the relationship is almost never queried and you only use cascade deletes for cleanup.
Key Decisions at a Glance: Trade-offs
| Decision | When to choose | Trade-offs |
|---|---|---|
| Surrogate key (auto-increment INT, UUID) | Most cases, especially when key has no business meaning | No natural connection to real-world data |
| Natural key (SSN, email, SKU) | When the identifier already exists and is stable | Changes in the real world force schema changes |
| Composite key | Junction tables, multi-column identifiers | Verbose foreign key references, complex joins |
| Single-column surrogate + natural unique index | When both matter | Adds a column you have to index anyway |
| ON DELETE CASCADE | Child rows have no independent meaning | May change many rows; measure the full cascade path |
| ON DELETE SET NULL | Optional relationships | Requires the FK column to be nullable |
| ON DELETE RESTRICT | When child must outlive parent | Prevents legitimate deletions |
| Defer FK enforcement to app layer | Ultra high-throughput write paths | You own the integrity — mistakes are permanent |
For many transactional schemas, a surrogate primary key with separate unique constraints for stable business identifiers is a useful starting point. Staging and append-only tables can have different needs; choose the smallest set of constraints that enforces the table’s actual identity and relationships.
Common Production Failures
Cascade delete on a large relationship: A parent delete with CASCADE changes every referencing row along the configured cascade path. The engine locks rows it needs to modify, and competing work may wait; the exact lock scope and duration depend on the database, indexes, transaction, row count, and concurrent workload. Review the dependency path, measure on production-sized data, and use an approved batch, archive, or soft-delete plan when one transaction would be too disruptive.
Missing indexes on foreign keys: A foreign key does not guarantee that the referencing columns have an index. Without one, a database may need to scan child rows to check references during a parent delete or update, or the query planner may choose a scan for a join. It is not true that every join will scan the whole table: plans depend on the engine, data size, selectivity, available indexes, and query. Inspect plans and test representative parent updates/deletes before deciding whether to add the index.
Deferring integrity to the application: When teams disable foreign key constraints for performance and handle integrity in application code, one bug or oversight corrupts data permanently. The application layer is the wrong place for referential integrity — it is not transactional and it is not enforced for direct SQL access. If constraints are disabled for a bulk load, re-enable them immediately after and validate.
Surrogate key changes: When a surrogate key is used as a natural identifier (like an order number derived from the auto-increment ID), and that ID changes, every foreign key reference breaks. Once an ID leaves the system — in a URL, an email, a printed invoice — it cannot change. Use immutable identifiers for external-facing references.
Real-World Case Study: GitHub and Rails Primary Key Migration
GitHub ran MySQL with INT SIGNED as primary keys for years. When they hit 2^31 - 1 on their user ID sequence, they had to migrate every table to BIGINT. This is not a theoretical problem — it bit them in 2012 and forced a massive cross-schema migration.
Their lesson: surrogate key type selection has a long tail. They chose INT early because it seemed reasonable at the time. By the time the problem surfaced, they had millions of rows and hundreds of foreign key relationships. The migration took months of planning and had to be executed in ways that avoided locking production tables.
The equivalent problem with UUIDs is storage and index bloat. UUIDs are 16 bytes versus 4 for an INT. On a table with 500 million rows, switching from INT to UUID surrogate keys adds roughly 6 GB of storage per index. For composite keys involving multiple UUIDs, the overhead multiplies. GitHub’s subsequent move to BIGINT was less painful than a full UUID migration would have been.
The broader lesson: pick your key type for where you expect the data to be in five years, not where it is today. And understand what your ORM defaults to — Rails historically used INT for id columns, which worked until it did not.
When Keys Matter Most
Keys matter most in write-heavy workloads. Every insert, update, and delete must maintain key constraints. For read-heavy analytical workloads, keys add overhead without proportionate benefit if you never enforce relationships at the database level.
OLTP systems need strong key enforcement. Analytical systems and data warehouses often skip foreign keys entirely, loading data that is already cleaned and validated. Know your workload and choose accordingly.
For more on how tables connect, see the guide on joins and relationships. To understand how keys fit into broader schema design, explore schema design and relational databases.
Real-world Failure Scenarios
Scenario 1: Cascade delete contention
Example: A support engineer deletes a test customer in a staging database. The customer has years of test orders, order items, shipment records, and audit rows. A cascade path can modify many dependent rows and make concurrent writes wait, depending on the engine, indexes, and workload.
What to check: Confirm the full set of cascading constraints, estimate the affected rows with queries, and rehearse the delete against a production-sized copy. The result is specific to that database and workload; do not assume a fixed lock scope or duration from a small development dataset.
Safer approach: Use RESTRICT when child records need an explicit disposition. If deletion is intended, apply the agreed child-row policy in bounded transactions and verify affected counts and post-conditions. Test the exact engine behavior before production.
Scenario 2: The UUID Primary Key That Bloat the Index
What happened: A microservices architecture adopted UUIDs as primary keys across all services for distributed ID generation. After 6 months, storage costs doubled and query performance degraded significantly. The database team discovered B-tree indexes on UUID columns were causing severe page splits and index bloat.
Root cause: UUIDs are 16 bytes versus 4 for integers, and their random distribution causes new rows to be inserted into random positions in the B-tree, causing constant page splits and index fragmentation. The index was not fitting in memory efficiently.
Impact: Storage costs increased by 15GB across production databases. Query latency p99 increased from 20ms to 150ms due to index bloat causing extra disk I/O.
Lesson learned: Random UUIDv4 values can make inserts less sequential in a B-tree index, and UUIDs take more space than a 32-bit integer key. If index locality matters, check whether the database version supports an ordered UUID generator and what ordering it guarantees; otherwise, consider an identity key. Benchmark with realistic data before choosing a primary-key format.
Scenario 3: A natural-key format changes
Example: A book catalog uses ISBN as its primary key and exposes it in URLs and partner feeds. If the system adopts ISBN-13 while older consumers still send ISBN-10, lookups and references can fail unless both formats are handled during a planned transition.
What to check: Find every database, API, report, and partner integration that stores the identifier. Define how old and new values map before changing the schema or external contract.
Safer approach: Use a stable internal key when external identifiers may change, and enforce the ISBN as a separate unique identifier under the rules that apply to the catalog. Treat the format change as a data and API migration, not just a column edit.
Interview Questions
A primary key enforces uniqueness and non-NULL values, and a table can have only one. It is backed by a unique index, but physical clustering is engine-specific: InnoDB stores rows in primary-key order, while PostgreSQL does not automatically cluster rows by its primary key. Unique-constraint NULL behavior also differs by database. Use a primary key when the table needs a declared row identity and a separate unique constraint for other identifiers.
First identify the database engine, cascade path, matching child rows, indexes, and retention requirements. A cascade changes matching rows and can make concurrent work wait, but it does not have one universal table-lock behavior or runtime. If child records need to remain, do not set the foreign key to NULL or a placeholder unless that state is valid in the data model. Use RESTRICT to force an explicit disposition, then archive, anonymize, or delete child records in tested transactions. If the business approves a cascade, rehearse it against representative data and check affected row counts and lock waits.
Natural keys make sense when the business already has a stable identifier that lives outside the database. An ISBN for books is a decent natural key — it exists before the book enters your system and it uniquely identifies the book. A SKU that is printed on physical products and used across multiple systems is another good candidate. The risk is that natural keys can change. If the ISBN system changes, your key changes. If a customer changes their email address (the natural key), every foreign key reference breaks. Natural keys work best when the identifier is truly immutable and genuinely unique.
The risk is data corruption. With FK constraints disabled, you can insert orders with customer_id values that do not exist, and the database will happily accept them. Those orphaned rows silently accumulate. The mitigation is to disable constraints only for the bulk load window, then re-enable them immediately after, running a validation query to confirm no orphaned rows exist before re-enabling. Never ship production code with constraints disabled as a "performance optimization."
ON DELETE CASCADE deletes the referencing rows when the parent row is deleted — removing a customer removes all their orders. ON DELETE SET NULL sets the foreign key column to NULL instead of deleting the rows — removing a customer leaves their orders in the table but without a customer reference. CASCADE is appropriate when the child rows should not exist without their parent. SET NULL is appropriate when the relationship is optional and the child rows should survive even if the parent is removed. SET NULL requires the FK column to be nullable.
A composite primary key uses multiple columns to uniquely identify a row. The combination of columns is unique, but individual columns may repeat. Use composite keys for junction tables in many-to-many relationships — PRIMARY KEY (order_id, product_id) ensures each product appears once per order. Composite keys are also appropriate when no single column is naturally unique but the combination is. Trade-offs: foreign key references to composite keys are verbose (must specify all columns), and queries that filter on only one column of the composite cannot use the index efficiently.
Every INSERT and UPDATE on a child table must check that the foreign key value exists in the parent table. Every DELETE on a parent table must check for referencing rows (unless CASCADE is set). This check requires at least an index lookup, sometimes a full scan if no index exists. For high-throughput write paths with millions of inserts per day, FK constraint overhead accumulates. Some high-performance systems defer integrity checks to the application layer — this trades safety for speed and requires the application to enforce integrity perfectly.
An index on a child foreign-key column can make joins and parent deletes more efficient, but the optimizer chooses a plan based on table size and statistics. Without a suitable index, the engine may scan the child table to find matches; it does not necessarily scan once for every parent row. Some engines create a supporting index automatically, while PostgreSQL does not. Check the schema and workload, then measure before adding or omitting an index.
Both prevent an update or delete that would leave invalid references. PostgreSQL checks RESTRICT immediately; non-deferrable NO ACTION is checked at statement end, and a DEFERRABLE NO ACTION constraint can be checked later in the transaction. MySQL InnoDB treats NO ACTION as an immediate RESTRICT check. Confirm the target engine's behavior before relying on deferred checks.
Surrogate keys (auto-increment INT, UUID) are database-generated and have no meaning outside the database, making them portable across database engines. Natural keys (SSN, ISBN) exist independently and may have different formats or constraints in different databases. If you use INT surrogate keys and later migrate from MySQL to PostgreSQL, the key values are preserved. If you use VARCHAR natural keys that were unique in MySQL, they might not port cleanly if the target database has different case sensitivity or encoding rules. Surrogate keys reduce portability risk for the key itself, though other schema elements may still pose challenges.
Primary key size matters for two reasons: storage and index performance. A B-tree index on a UUID column (16 bytes) is larger than on an INT (4 bytes). For a table with 500 million rows, an INT primary key index is roughly 2 GB while a UUID index is roughly 8 GB. Additionally, UUIDs inserted randomly cause page splits and index fragmentation. Size also matters when the primary key is used as a foreign key in child tables — larger FK columns multiply storage costs. For extreme scale, consider whether a BIGINT or composite key of two INTs is more efficient than UUIDs.
Updating a primary key can require changes to the key index and, when cascading is configured, each matching child reference. That work may hold locks and contend with other transactions; exact behavior depends on the engine and schema. Surrogate keys are usually treated as stable by convention. If a natural key must change, plan the referencing-row updates and rehearse them with representative data.
Clustering is engine-specific. InnoDB organizes table rows by its clustered primary-key index. PostgreSQL creates a primary-key index but does not keep the table physically ordered by it; its CLUSTER command is separate, and later writes do not maintain that order. SQL Server lets the table's clustered index be chosen separately from the primary-key constraint. Consider insertion pattern and key width for the target engine rather than assuming every primary key controls row placement.
Use a natural unique constraint (not primary key) when the business identifier has meaning but should not be the row identifier. An email address is a good example — it is unique and meaningful, but using it as the primary key means every foreign key in the system carries a 255-character string. A surrogate INT as primary key with a UNIQUE constraint on email keeps the business identifier enforced while keeping the internal reference compact. This separates the internal identifier from the external contract.
ON UPDATE CASCADE propagates an allowed parent-key change to its foreign-key references. It can fit a natural key that the domain expects to change, though many systems instead use a surrogate primary key and keep the changing business identifier in a separate unique column. Surrogate keys are usually left unchanged by convention; the database does not make them immutable just because they are surrogates.
Distributed databases cannot use auto-increment INT because different nodes might generate the same value. Options: UUID (16 bytes, globally unique but large and random), UUID v7 (time-ordered for better B-tree performance), snowflake IDs (64-bit with timestamp, machine ID, and sequence), and key generation services (centralized ticket servers). Choose based on whether you need time ordering (affects B-tree performance), whether IDs cross system boundaries (requires global uniqueness), and storage constraints (16 bytes vs 8 bytes).
A cascade can modify many dependent rows, so it may hold locks and make conflicting work wait until the transaction finishes. The lock scope and duration depend on the engine, schema, indexes, row count, and concurrent activity; there is no universal number or promise that entire child tables are locked. Rehearse the operation, inspect row counts and lock waits, and choose an explicit archive, soft-delete, batch, RESTRICT, or CASCADE policy based on the data lifecycle.
Primary key constraints cannot contain NULL — the constraint explicitly requires a value. Unique constraints allow one NULL (or multiple NULLs depending on the database since NULL != NULL). This matters for columns that are genuinely optional. If a column should be unique when populated but may be absent, use a unique constraint with a partial index or a filtered unique index (PostgreSQL) rather than a primary key. The database treats one NULL as unknown and allows multiple NULLs in unique constraints because NULL is not equal to itself.
Constraint names appear in error messages and system catalogs. A constraint named "fk_orders_customers" immediately communicates which tables and columns are involved. A constraint named "a3k9d2" requires a lookup. Explicit naming conventions also prevent name collisions — two tables might both have an "fk_orders_customer_id" if you do not qualify the table name. Standard naming (pk_