PostgreSQL Foreign Key: ALTER TABLE, CASCADE Rules, and Indexing
For developers who write PostgreSQL DDL and are adding foreign keys to tables that already hold data.
On this page
A PostgreSQL foreign key makes the database refuse a row whose column value matches no key in another table. For example, PostgreSQL then refuses an order whose customer id matches no customer.
If foreign keys are new to you, read What is a foreign key first. Here you add one to a PostgreSQL table that already holds rows, choose what a delete does, and index the child column.
ALTER TABLE adds a foreign key to an existing table:
ALTER TABLE child_table
ADD CONSTRAINT constraint_name
FOREIGN KEY (child_column)
REFERENCES parent_table (parent_column)
ON DELETE action
ON UPDATE action
NOT VALID;
child_tableholds the reference, andparent_tableis the table that it points at.CONSTRAINT constraint_namenames the foreign key. Error messages show the name, and DROP CONSTRAINT needs it.FOREIGN KEY (child_column)lists the child's columns. A foreign key on several columns lists them in the same order as the parent's columns after REFERENCES.REFERENCES parent_table (parent_column)names the parent's columns. A primary key or a unique constraint must cover these parent columns.ON DELETEandON UPDATEset what happens to the child rows when a parent row is deleted or its key changes. Both are optional. The default, NO ACTION, refuses the delete or the key change while child rows point at the parent row.NOT VALIDskips the check of the rows already in the table. It is optional too.
In CREATE TABLE, write the same clause, without NOT VALID, after the last column. A shorter form puts REFERENCES parent_table (parent_column) right after a column's type. With the shorter form, PostgreSQL names the constraint <table>_<column>_fkey from the table's name and the column's name.
Create two sample tables, authors and books, and fill them:
CREATE TABLE authors (
author_id int PRIMARY KEY,
name text NOT NULL
);
CREATE TABLE books (
book_id int PRIMARY KEY,
title text NOT NULL,
author_id int NOT NULL
);
INSERT INTO authors VALUES
(1, 'Ada'),
(2, 'Grace');
INSERT INTO books VALUES
(10, 'Structured Design', 1),
(11, 'Numerical Methods', 2),
(12, 'Notes on Compilers', 9);
books is the child table, and its author_id will point at authors.author_id. Book 12 names author 9, and no author has that id.
Every statement below ran on PostgreSQL 18.6. Run the statements in order, because several of them change the rows of books.
Practice this: Lesson 8 of the SQL tutorial shows on a shop database in your browser which rows a primary key and a foreign key refuse, with exercises.
ADD CONSTRAINT
ADD CONSTRAINT adds a foreign key to a table that already holds rows. For example, you can add a foreign key from books.author_id to authors.author_id.
ALTER TABLE books ADD CONSTRAINT fk_books_author
FOREIGN KEY (author_id) REFERENCES authors (author_id);
ERROR: insert or update on table "books" violates foreign key constraint "fk_books_author"
DETAIL: Key (author_id)=(9) is not present in table "authors".
PostgreSQL checks every row of books before it creates the foreign key. Book 12 names author 9, so the statement fails, and books gets no foreign key. The error names one bad row, even when there are several.
NOT VALID
NOT VALID adds the foreign key without checking the rows already in the table. For example, you can add fk_books_author while book 12 still names a missing author.
ALTER TABLE books ADD CONSTRAINT fk_books_author
FOREIGN KEY (author_id) REFERENCES authors (author_id)
NOT VALID;
INSERT INTO books VALUES (13, 'Lambda Papers', 99);
ERROR: insert or update on table "books" violates foreign key constraint "fk_books_author"
DETAIL: Key (author_id)=(99) is not present in table "authors".
The ALTER TABLE succeeded, and book 12 is still in books. The INSERT failed, because PostgreSQL checks every new row against the foreign key. The old rows stay unchecked until you validate the foreign key (ALTER TABLE).
VALIDATE CONSTRAINT
VALIDATE CONSTRAINT checks the existing rows against a foreign key that you added with NOT VALID. For example, you can check whether every book already in books has an author.
ALTER TABLE books VALIDATE CONSTRAINT fk_books_author;
ERROR: insert or update on table "books" violates foreign key constraint "fk_books_author"
DETAIL: Key (author_id)=(9) is not present in table "authors".
Book 12 still names author 9, so the check fails. The foreign key stays in place and keeps refusing new bad rows. Fix the rows that have no parent, then run VALIDATE CONSTRAINT again.
Find the rows without a parent
A LEFT JOIN that keeps only the rows with a NULL parent key returns the child rows without a parent. For example, you can list every book whose author is missing.
SELECT b.book_id, b.author_id
FROM books b
LEFT JOIN authors a ON a.author_id = b.author_id
WHERE a.author_id IS NULL;
| book_id | author_id |
|---|---|
| 12 | 9 |
The LEFT JOIN finds no author 9 for book 12, so a.author_id is NULL and the WHERE keeps the row. Point book 12 at an existing author, or delete it. Here, book 12 goes to Grace:
UPDATE books SET author_id = 2 WHERE book_id = 12;
ALTER TABLE books VALIDATE CONSTRAINT fk_books_author;
SELECT * FROM books ORDER BY book_id;
| book_id | title | author_id |
|---|---|---|
| 10 | Structured Design | 1 |
| 11 | Numerical Methods | 2 |
| 12 | Notes on Compilers | 2 |
VALIDATE CONSTRAINT now succeeds, and every book has an author. If the child column allows NULL, add AND b.author_id IS NOT NULL to the query. A NULL in the child column passes the foreign key, so it is not an error to fix.
ON DELETE CASCADE
ON DELETE CASCADE deletes the child rows together with their parent row. For example, deleting Ada then also deletes her book.
PostgreSQL can't change the action of an existing foreign key. Drop the foreign key and add it again, in one ALTER TABLE:
ALTER TABLE books
DROP CONSTRAINT fk_books_author,
ADD CONSTRAINT fk_books_author
FOREIGN KEY (author_id) REFERENCES authors (author_id)
ON DELETE CASCADE;
DELETE FROM authors WHERE author_id = 1;
SELECT * FROM books ORDER BY book_id;
| book_id | title | author_id |
|---|---|---|
| 11 | Numerical Methods | 2 |
| 12 | Notes on Compilers | 2 |
Book 10 belonged to Ada, so the DELETE removed it with her. Books 11 and 12 belong to Grace, and they stay. Under the default NO ACTION, deleting Ada fails, and she and book 10 stay.
Each action does this to the child rows when their parent row is deleted:
| Action | Child rows |
|---|---|
| NO ACTION, the default | the DELETE fails |
| RESTRICT | the DELETE fails |
| CASCADE | deleted with the parent |
| SET NULL | the child column becomes NULL |
| SET DEFAULT | the child column takes its default |
ON UPDATE takes the same actions when a parent's key changes. ON UPDATE CASCADE copies the new key into the child rows. SET DEFAULT fails when no parent row has the default value.
RESTRICT and NO ACTION
RESTRICT refuses to delete a parent row while child rows point at it. For example, with RESTRICT, PostgreSQL refuses to delete Grace while books 11 and 12 name her.
ALTER TABLE books
DROP CONSTRAINT fk_books_author,
ADD CONSTRAINT fk_books_author
FOREIGN KEY (author_id) REFERENCES authors (author_id)
ON DELETE RESTRICT;
DELETE FROM authors WHERE author_id = 2;
ERROR: update or delete on table "authors" violates RESTRICT setting of foreign key constraint "fk_books_author" on table "books"
DETAIL: Key (author_id)=(2) is referenced from table "books".
The error names RESTRICT. Under NO ACTION, the error says "violates foreign key constraint" and doesn't name RESTRICT. NO ACTION and RESTRICT also differ in when PostgreSQL checks.
A NO ACTION foreign key declared DEFERRABLE INITIALLY DEFERRED is checked at COMMIT, not after each statement. Inside one transaction, you can then insert a book before its author. The PostgreSQL 18 documentation says that RESTRICT "does not allow the check to be deferred".
Index the child column
An index on the child column lets PostgreSQL find a parent's child rows without reading the whole child table. For example, deleting an author then looks up her books through the index.
SELECT indexname FROM pg_indexes WHERE tablename = 'books';
| indexname |
|---|
| books_pkey |
Only the primary key of books has an index. The PostgreSQL documentation says that a foreign key "does not automatically create an index on the referencing columns", the columns of the child table. Create it yourself:
CREATE INDEX idx_books_author_id ON books (author_id);
Without this index, each DELETE from authors reads all of books to find the books that still name the author. Skip the index only where parent rows are never deleted, their keys never change, and no query joins on the column. PostgreSQL Create Index and Indexes and Foreign Keys explain the choice in detail.
List foreign keys with pg_constraint
The catalog table pg_constraint holds one row for each constraint, and contype = 'f' marks a foreign key. conrelid::regclass prints the name of the constraint's table. For example, you can list every foreign key of the database with its definition.
SELECT conrelid::regclass AS table_name, conname, pg_get_constraintdef(oid)
FROM pg_constraint
WHERE contype = 'f';
| table_name | conname | pg_get_constraintdef |
|---|---|---|
| books | fk_books_author | FOREIGN KEY (author_id) REFERENCES authors(author_id) ON DELETE RESTRICT |
fk_books_author is the only foreign key, and pg_get_constraintdef prints its definition with the RESTRICT action. In psql, \d books shows the same line under "Foreign-key constraints". Describe Table in PostgreSQL reads the rest of that output.
What goes wrong
ADD CONSTRAINT blocks writes on both tables
ADD CONSTRAINT locks the child table and the parent table. The ALTER TABLE documentation names these locks, and the table of lock conflicts says what each one blocks:
| Statement | Lock on books | Lock on authors | Statements it blocks |
|---|---|---|---|
ADD CONSTRAINT | SHARE ROW EXCLUSIVE | SHARE ROW EXCLUSIVE | INSERT, UPDATE and DELETE, for the whole check |
ADD CONSTRAINT ... NOT VALID | SHARE ROW EXCLUSIVE | SHARE ROW EXCLUSIVE | INSERT, UPDATE and DELETE, briefly |
VALIDATE CONSTRAINT | SHARE UPDATE EXCLUSIVE | ROW SHARE | none of SELECT, INSERT, UPDATE and DELETE |
DROP CONSTRAINT | ACCESS EXCLUSIVE | ACCESS EXCLUSIVE | SELECT, INSERT, UPDATE and DELETE |
On a large table, add the foreign key with NOT VALID, and validate it afterwards. The check of the old rows then runs while reads and writes go on.
To change an action on a large table, end the ADD CONSTRAINT that follows the DROP CONSTRAINT with NOT VALID, and validate afterwards. Without NOT VALID, that ALTER TABLE holds ACCESS EXCLUSIVE on both tables for the whole check.
The parent column has no unique constraint
ALTER TABLE books ADD COLUMN author_name text REFERENCES authors (name);
ERROR: there is no unique constraint matching given keys for referenced table "authors"
authors.name has no primary key and no unique constraint, so PostgreSQL refuses the foreign key. A unique index without a WHERE clause works too, but a non-unique index doesn't.
Foreign keys in DbSchema
DbSchema draws each foreign key as a line between two tables. Connect DbSchema to PostgreSQL, and DbSchema shows the tables of the schema on a diagram.
To add a foreign key, drag books.author_id onto authors.author_id. DbSchema opens the New Foreign Key dialog with the columns filled in, where On Delete and On Update set the actions.
On the dialog's Optimizations tab, Optimize deletions by indexing the referring column(s) also creates the index on the child column (Foreign Keys).
When DbSchema is connected, pressing OK creates the foreign key in the database at once. Offline, the foreign key stays in the DbSchema model until you synchronize the model with the database, which needs DbSchema Pro.
Download DbSchema at https://dbschema.com/download.html and connect it to your PostgreSQL database: each line on the diagram is a foreign key. Two tables that share a column such as author_id, with no line between them, have no foreign key yet. The free Community Edition covers connecting, the diagram and creating foreign keys in a connected database.

