You set a foreign key by making one table’s column (or columns) reference a candidate key—usually the primary key—of another table, then enforcing that relationship with a constraint. In table design, decide the relationship and delete/update behavior before writing DDL: define the parent key first, create the child table with a matching data type, and name the constraint so future changes are traceable. The constraint only protects rows going forward—it doesn’t validate or repair data that already violates the rule.

That distinction matters more than most syntax guides admit. A foreign key is not merely a join hint. It’s an integrity rule enforced by the database engine, and its behavior depends on the storage engine, column types, indexing, and the referential actions you choose. Getting the design right means thinking about cardinality, optionality, keys, and lifecycle before you type REFERENCES.

This guide covers the design decisions first, then the DDL, then verification, and finally the traps that cause production incidents: orphaned data, mismatched types, lock-heavy cascades, and keys that seem equivalent but aren’t.

What a foreign key actually enforces

A foreign key constraint says: for every non-null value in the child column, a row with that value must exist in the parent’s referenced key. The database checks this on insert and on update of the child column, and it blocks deletion or key changes in the parent that would leave child rows dangling—unless you’ve specified an action that resolves the conflict.

Three properties follow from that definition:

Nulls are exempt. In standard SQL, a composite foreign key with any null component is generally not checked (MATCH SIMPLE, the default). A single nullable foreign key column allows “no relationship” rows. If the relationship is mandatory, make the column NOT NULL. The parent side must be uniquely identifiable. Most engines require the referenced columns to form a primary key or a unique constraint. MySQL/InnoDB is stricter than the standard here: the referenced columns must be the leftmost columns of an index, and in practice a unique key is what you want. Enforcement is per statement, not per transaction, in common engines. A statement that temporarily violates the rule fails even if a later statement in the same transaction would fix it—unless the constraint is declared deferrable, which most mainstream engines (MySQL, SQL Server, SQLite) don’t support. PostgreSQL supports DEFERRABLE INITIALLY DEFERRED, which lets you violate the rule mid-transaction as long as it holds at commit.

That last point shapes migration strategy. If you need to load parent and child rows in an order that temporarily breaks references, PostgreSQL’s deferrable constraints or a staged load with constraints added afterward are the usual answers.

Design first: cardinality, optionality, and the right key

Before writing any DDL, answer four questions. The answers determine the column placement and the constraint’s shape.

  1. What is the cardinality? One-to-many is the classic case: an orders table references customers. Many-to-many needs a junction table—product_tags(product_id, tag_id) with two foreign keys and a composite primary key—not two foreign keys crammed into one table. One-to-one is usually a foreign key with a unique constraint on the child column, or simply merged tables.

  2. Is participation mandatory? A nullable foreign key models “may have a parent.” Ask whether a row without a parent is meaningful. An order without a customer is usually invalid; an employee without a manager (the CEO) is valid, so manager_id should be nullable and the table self-references.

  3. Which parent key? Prefer the parent’s primary key, which is stable and indexed. Natural keys (email, ISBN, country code) look convenient but change—emails get corrected, codes get reorganized—and a changing parent key forces cascading updates through every child. Surrogate integer or UUID keys avoid that. If you do reference a natural key, add a unique constraint on it and accept that updates to it will need ON UPDATE handling.

  4. What should happen when the parent is deleted or its key changes? This is the referential action decision, covered in its own section below. Decide it per relationship, not globally.

A worked example makes the placement concrete. Suppose you’re modeling customers and orders. customers.id is the parent key. orders.customer_id is the child column, declared with the same type as customers.id, indexed, and NOT NULL because every order needs a customer. The constraint goes on orders, pointing at customers.

Writing the DDL: inline versus table-level constraints

There are two syntactic placements, and they’re equivalent in effect but differ in readability and in how you handle composite keys.

Inline (column-level):

Table-level (out-of-line), which is required for composite foreign keys and preferred when you want to name the constraint:

For a composite key, list the columns in matching order:

Name your constraints. Auto-generated names differ across engines and make ALTER TABLE ... DROP CONSTRAINT a guessing game during migrations. A convention like fk__ pays for itself the first time you need to drop one.

Adding a foreign key to an existing table uses ALTER TABLE:

The table must already contain no violating rows, or the ALTER fails. The next section covers what to do about that.

Referential actions: choosing what happens on delete and update

The ON DELETE and ON UPDATE clauses define the resolution when the parent key is removed or changed. There are five standard actions, and the differences are consequential.

Action Effect on child rows when parent is deleted Typical use
RESTRICT / NO ACTION Delete is blocked if child rows exist Default safety; protect referenced master data
CASCADE Child rows are deleted too Owned detail rows: order → order_lines
SET NULL Child foreign key column set to null Optional relationship: employee → manager
SET DEFAULT Child column set to its declared default Rare; requires a valid default row to exist
NO ACTION (deferred) Same as restrict for immediate constraints; checked at statement or commit PostgreSQL deferrable patterns

A few practical distinctions:

RESTRICT and NO ACTION behave identically for immediate constraints in most engines. The difference surfaces with deferrable constraints, where NO ACTION can be postponed to commit. CASCADE is a design commitment, not a convenience. Deleting a customer that cascades to orders, which cascade to order lines, which cascade to shipments, is a multi-table deletion triggered by one statement. That can be correct for owned data and catastrophic for shared reference data. Never put ON DELETE CASCADE on a foreign key pointing at a lookup table like countries or currencies. SET NULL requires the child column to be nullable; the DDL fails otherwise. SET DEFAULT requires the default value to satisfy the constraint at the time of deletion, which is why it’s rarely used—in practice the default row often doesn’t exist.

Self-referencing foreign keys deserve a note. An employees.manager_id referencing employees.id with ON DELETE SET NULL means deleting a manager orphans their reports into the null state rather than deleting them. With CASCADE, you’d delete the entire reporting subtree—almost never what you want. Choose deliberately.

Making sure the constraint can actually be created

Most foreign key failures happen before the constraint exists. Check these in order; each is a reversible diagnostic step.

  1. Data type match. The child and parent columns must be compatible. INT versus BIGINT often works, but INT versus VARCHAR never will. Watch for signed/unsigned mismatches in MySQL (INT versus INT UNSIGNED), which fail with an errno 3780-style error, and for collation mismatches on string keys. The safest rule: make the child column the exact same type as the parent, including length, signedness, and collation.

  2. Existing violating rows. Run a check before adding the constraint:

Any rows returned must be resolved—either insert the missing parents, correct the child values, or set them to null if the relationship is optional. Only then run the ALTER TABLE.

  1. Index on the child column. Most engines require an index on the referencing columns, and some create one implicitly; others don’t. MySQL/InnoDB auto-creates an index if none exists, which can silently add storage and write overhead. PostgreSQL does not require one, but without it, parent deletes and updates do full scans of the child table to check for references. Add the index explicitly so it’s named and sized deliberately:

  2. Parent key uniqueness and engine support. Confirm the referenced columns carry a primary key or unique constraint. In MySQL, confirm the table is InnoDB—the older MyISAM engine parses foreign key syntax and ignores it entirely, which produces a constraint that appears to exist and enforces nothing.

  3. Privileges and locking. You need REFERENCES privilege on the parent table in PostgreSQL and appropriate DDL rights elsewhere. On large tables, adding a foreign key can take a lock and scan the child table; plan it for a maintenance window or use the engine’s online-DDL options where available.

A success check after creation: attempt an insert with a nonexistent parent id and confirm it’s rejected. Then attempt to delete a referenced parent without a cascading action and confirm that’s rejected too. If both fail as expected, the constraint is live.

Verifying and auditing existing foreign keys

Constraints are easy to create and easy to lose track of. Each engine exposes them differently, and the inspection queries are worth keeping.

PostgreSQL: \d+ orders in psql shows constraints; information_schema.table_constraints and information_schema.referential_constraints give the catalog view, including the delete/update rules. MySQL: SHOW CREATE TABLE orders prints the full constraint definition; information_schema.KEY_COLUMN_USAGE and REFERENTIAL_CONSTRAINTS give a queryable list. SQL Server: sys.foreign_keys and sys.foreign_key_columns; also visible in the object explorer. SQLite: PRAGMA foreign_key_list(orders); lists them—and note that SQLite enforces foreign keys only when PRAGMA foreign_keys = ON; is set per connection. A connection that never enables it will happily insert orphans.

That last point generalizes: enforcement is a connection-level or engine-level setting in some systems, not a property of the schema alone. Verify enforcement behavior, not just the presence of the constraint.

For auditing, the query that finds orphans is the same one used before creation, run periodically on tables where constraints were added after data existed or where application bugs might bypass them. Some teams schedule it as a data-quality check.

Common design mistakes and their consequences

Mismatched types. A VARCHAR(10) child referencing a VARCHAR(20) parent may work in some engines and fail in others, and even when it works it can prevent index use. Match types exactly.

Missing index on the child column. Parent deletes become slow as the child table grows, because each delete scans for references. The fix is a simple CREATE INDEX, but it’s easy to overlook because the constraint itself works fine.

Cascades chained through shared data. ON DELETE CASCADE on a foreign key to a lookup table means deleting a country deletes every customer in it. Restrict shared reference data; cascade only owned detail rows.

Nullable foreign keys used as a soft-delete mechanism. Setting customer_id to null to “remove” the relationship loses history. If you need to retain the link, use a status column instead.

Referencing a non-unique column. Some engines reject this outright; others allow it in narrow circumstances. Either way, a foreign key to a non-unique parent key is a design error, because the reference is ambiguous.

Assuming a foreign key is a performance feature. It’s an integrity feature. It doesn’t create a join index on the parent side (the parent key is already indexed) and it does add write-time checks on the child. The performance benefit—faster parent deletes—comes from the child index, not the constraint.

Forgetting about load order in bulk imports. Loading child rows before parents fails. Either order the load correctly, use deferrable constraints where supported, or load into staging tables and add constraints after the data is clean.

Each of these is fixable, but the fix cost rises with table size and data volume. The design decisions are cheap; the retrofits are not.

When foreign keys are the wrong tool

Foreign keys don’t fit every design, and pretending otherwise causes friction.

Sharding and distributed databases. A foreign key can’t span shards. If orders lives on one node and customers on another, the constraint is unenforceable. Cross-shard referential integrity is typically handled at the application layer or by co-locating related rows.

Very high write throughput. Every child insert triggers a parent-key lookup and a lock check. In systems where that overhead is measurable, teams sometimes drop constraints and enforce integrity in application code—accepting that orphans become possible and that audits are now mandatory.

Soft deletes and versioned rows. If parents are never physically deleted, ON DELETE actions rarely fire, and the constraint mostly guards against bad inserts. That’s a legitimate use, but know which half of the rule you’re relying on.

Polymorphic references. A comments table that points at either posts or photos via a target_type column can’t use a single foreign key. The standard relational fix is separate nullable foreign keys per target type (with a check constraint ensuring exactly one is set), or separate junction tables.

Data warehouses and analytical stores. Columnar warehouses often don’t enforce foreign keys even when they accept the syntax. Declaring them documents intent; it doesn’t guarantee integrity. Verify enforcement before relying on it.

The general principle: a foreign key is a promise the database keeps. When the database can’t keep the promise—because of distribution, throughput, or schema shape—enforce it elsewhere and be explicit about the trade.

FAQ

Can a foreign key reference a non-primary unique column? Yes, in most engines, provided the referenced columns have a unique constraint. But prefer the primary key: unique natural keys change, and updates to them ripple through child rows.

Do I need an index on the foreign key column? You need one for performance, and some engines create it automatically. PostgreSQL doesn’t, so add it explicitly. The index speeds up parent deletes and joins that start from the child side.

What’s the difference between RESTRICT and NO ACTION? For immediate constraints in most engines, nothing observable. With deferrable constraints, NO ACTION can be deferred to commit while RESTRICT cannot.

Can I add a foreign key to a table with existing orphaned rows? No—the ALTER fails. Find and fix the orphans first, then add the constraint, then verify enforcement.

Does SQLite enforce foreign keys by default? No. Enforcement requires PRAGMA foreign_keys = ON; on each connection. Without it, the constraint is declared but inactive.

What happens if I delete a parent row with a RESTRICT constraint? The delete is rejected with an error, and the parent row remains. That’s the intended safety behavior for referenced master data.