FOREIGN KEY Constraint

Last updated: 2026-11-04

FOREIGN KEY Constraint

A foreign key enforces referential integrity: every child row must point at a row that really exists in the parent. When a parent row is deleted or updated, ON DELETE and ON UPDATE decide the child's fate — CASCADE removes it, SET NULL blanks the reference, RESTRICT refuses the operation. The constraint can also be declared DEFERRABLE, deferring the check until commit time.

Kindconstraint
Example LanguageSQL

📝 Syntax

`FOREIGN KEY (col) REFERENCES parent_table (parent_col)`
Referential actions: `ON DELETE` / `ON UPDATE` accept `CASCADE` | `SET NULL` | `SET DEFAULT` | `RESTRICT` | `NO ACTION`

⚙️ Parameters

colThe referencing column in the child table; its type must match the referenced column exactly (or be implicitly convertible).
referenced_table (referenced_col)The parent table and column. The referenced column must be the parent's primary key or carry a unique constraint.
ON DELETE / ON UPDATEHow child rows are handled when the parent row is deleted or updated; defaults to NO ACTION.

Returns:A foreign key has no return value. It blocks child rows from referencing a non-existent parent, and on violation PostgreSQL raises `insert or update on table "..." violates foreign key constraint "..."`.

▶ Example

Runs real PostgreSQL 18 right in your browser (PGlite WASM, nothing to install). Press ▶ Run and the result appears in the panel below.

Output:

SELECT 'ON DELETE CASCADE -> orders left' AS step, (SELECT count(*)::TEXT FROM orders) AS result
UNION ALL SELECT 'ON DELETE SET NULL -> address.customer_id', (SELECT customer_id::TEXT FROM addresses WHERE address_id = 1)
UNION ALL SELECT 'ON DELETE RESTRICT -> delete customer 3', (SELECT pg_try('DELETE FROM customers WHERE customer_id = 3'))
UNION ALL SELECT 'FK violation -> insert order with customer_id 999', (SELECT pg_try('INSERT INTO orders VALUES (99, 999)'))
 step                                              | result
---------------------------------------------------+---------------------------------------------------------------------------------------------------------------------------------------------
 ON DELETE CASCADE -> orders left                  | 0
 ON DELETE SET NULL -> address.customer_id         | NULL
 ON DELETE RESTRICT -> delete customer 3           | update or delete on table "customers" violates RESTRICT setting of foreign key constraint "contracts_customer_id_fkey" on table "contracts"
 FK violation -> insert order with customer_id 999 | insert or update on table "orders" violates foreign key constraint "orders_customer_id_fkey"
(4 rows)

📌 Key Points

More case studies coming soon.

📚 Related Reference

❓ FAQ

QShould I use CASCADE or SET NULL?
AUse CASCADE when the child row has no meaning without its parent (order lines vanish with the order); use SET NULL when the child survives but loses its association (a user's default address is cleared while the address record stays).
QHow do I read the foreign key violation error?
AThe message reads `insert or update on table "orders" violates foreign key constraint "orders_customer_id_fkey"`. The first half names the table and the operation; the second half gives the constraint name, which is the conname in pg_constraint, so you can look the definition up directly.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏