Sub topic 17
Deferrable Constraints and Circular References
This chapter assumes you can write CREATE TABLE statements with primary and foreign keys, and that you know how transactions work (BEGIN, COMMIT, ROLLBACK). The examples use PostgreSQL syntax.
When a constraint is checked
By default, a constraint is checked immediately. For a foreign key, the database tests every row change right after the statement runs, and it rejects the statement if the parent row is missing. This works for most schemas. It fails when two tables each need the other to exist first.
A deferrable constraint lets you postpone that check until the end of the transaction. Rows may break the rule in between, but the rule must hold when you COMMIT.
The three timing modes
You choose the mode when you declare the constraint.
| Declaration | Behavior |
|---|---|
| `NOT DEFERRABLE` (default) | Checked immediately. Cannot be postponed. |
| `DEFERRABLE INITIALLY IMMEDIATE` | Checked immediately unless a transaction asks to defer it. |
| `DEFERRABLE INITIALLY DEFERRED` | Checked at commit unless a transaction asks to check it earlier. |
Inside a transaction, SET CONSTRAINTS changes the timing of deferrable constraints:
SET CONSTRAINTS fk_departments_head DEFERRED;
SET CONSTRAINTS ALL IMMEDIATE;SET CONSTRAINTS ALL IMMEDIATE also runs any pending checks at that moment. Use it to find a violation before COMMIT does.
A circular reference
Suppose every department must have a head, and every staff member must belong to a department. Each table's foreign key points at the other. Neither row can be inserted first.
CREATE TABLE departments (
department_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name VARCHAR(100) NOT NULL,
head_id INTEGER NOT NULL
);
CREATE TABLE staff (
staff_id INTEGER GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
name VARCHAR(100) NOT NULL,
department_id INTEGER NOT NULL REFERENCES departments (department_id)
);
ALTER TABLE departments
ADD CONSTRAINT fk_departments_head
FOREIGN KEY (head_id) REFERENCES staff (staff_id)
DEFERRABLE INITIALLY DEFERRED;Only fk_departments_head needs to be deferrable. Once it is, you can insert a department first. The staff foreign key stays immediate, and it passes because the department row exists by then.
The department's head_id must point at a staff row that does not exist yet. The sequence behind staff_id supplies that number in advance. The staff row then reuses it. staff_id is declared BY DEFAULT so that you can pass an explicit value. A GENERATED ALWAYS column would reject it.
BEGIN;
INSERT INTO departments (name, head_id)
VALUES ('Engineering', nextval(pg_get_serial_sequence('staff', 'staff_id')));
INSERT INTO staff (staff_id, name, department_id)
VALUES (
currval(pg_get_serial_sequence('staff', 'staff_id')),
'Ada',
currval(pg_get_serial_sequence('departments', 'department_id'))
);
COMMIT;The first insert would fail if the constraint were not deferrable. PostgreSQL would report error 23503 (foreign_key_violation) because no staff row exists yet. With the deferral, the check runs at COMMIT. At that point the staff row is there, so the commit succeeds.
If you left out the second insert, the COMMIT would fail with the same error. The whole transaction would then be rolled back.
Other ways to break the cycle
Deferral is not the only fix. You should usually try these first.
- Make one foreign key nullable. Insert the department with
head_idset toNULL, insert the staff row, then update the department. This works in every database and needs no special syntax. The cost is that the schema no longer guarantees that a head exists. - Move the relationship into its own table. A
department_headstable with a foreign key to each side removes the cycle entirely. - Re-think the model. Many cycles come from storing one fact twice. "Head of department" could be a boolean
is_headonstaff, with a partial unique index to allow only one head per department.
Choose deferral when the rule really must be mandatory in both directions and you control every writer that touches those tables.
Deferring unique constraints
Foreign keys are not the only constraints you can defer. A unique constraint can also be deferrable, which solves the swap problem. Without deferral, swapping two values in a unique column can fail halfway because the intermediate state has a duplicate.
CREATE TABLE tasks (
task_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
position INTEGER NOT NULL,
CONSTRAINT uq_tasks_position UNIQUE (position) DEFERRABLE INITIALLY IMMEDIATE
);
INSERT INTO tasks (position) VALUES (1), (2);
UPDATE tasks SET position = 3 - position WHERE position IN (1, 2);A non-deferrable unique constraint is checked after each row. The swap above can fail on the first row, because it would briefly duplicate a position. A deferrable one is checked at the end of the statement, so the swap succeeds even in INITIALLY IMMEDIATE mode.
Gotchas
ON DELETE RESTRICTandON UPDATE RESTRICTare never deferred, even on a deferrable foreign key.NO ACTION, the default, can be deferred. Cascading actions (CASCADE,SET NULL,SET DEFAULT) run immediately, but any foreign key check they trigger follows the constraint's timing.- A foreign key cannot reference a deferrable unique or primary key constraint in PostgreSQL. Creating one fails. Keep the referenced key non-deferrable and defer only the foreign key.
- Errors appear late. A violation shows up at
COMMITand not at the statement that caused it, which makes debugging harder. UseSET CONSTRAINTS ALL IMMEDIATEto test for violations at a chosen point. INITIALLY DEFERREDchanges behavior for every writer, including code that never expected late errors.INITIALLY IMMEDIATEis safer because only transactions that opt in get deferred checking.- Deferred checks only protect you within a transaction. In autocommit mode each statement is its own transaction, so deferral gives no benefit.
Support across databases
| Database | Deferrable constraints |
|---|---|
| PostgreSQL | Yes, for foreign keys, unique, primary key, and exclusion constraints. |
| Oracle | Yes, with `DEFERRABLE INITIALLY DEFERRED` and `SET CONSTRAINTS`. |
| SQLite | Foreign keys only, and foreign key enforcement must be turned on with `PRAGMA foreign_keys = ON`. |
| MySQL (InnoDB) | No. Constraints are checked per statement. |
| SQL Server | No. Use a nullable column and a later update. |
If you must support MySQL or SQL Server, plan for the nullable-column approach from the start.
Exercise
A table a has a NOT NULL foreign key to b, and b has a NOT NULL foreign key to a. Both are NOT DEFERRABLE. Which minimal change lets you insert the first pair of rows, and what must be true at COMMIT?
Show answer
Make one of the two foreign keys DEFERRABLE (for example INITIALLY DEFERRED), and keep the other as it is. In one transaction, insert the row whose foreign key is deferred first, pointing at the key value the other row will have. Then insert the other row, which passes its immediate check because the first row exists. At COMMIT, the deferred foreign key is checked and the matching row must exist. Otherwise the commit fails and the whole transaction rolls back.