Sub topic 8
What referential integrity rejects
This chapter assumes you can write basic INSERT, UPDATE, and DELETE statements and can create tables with CREATE TABLE. It also assumes you have seen a PRIMARY KEY and a REFERENCES clause. Here you will learn exactly which statements a foreign key blocks, what the error looks like, and the edge cases that surprise people. The examples use PostgreSQL syntax.
The rule in one sentence
Referential integrity means every non-NULL value in a foreign key column must match an existing value in the key column it references. The database checks this rule on every statement that could break it. A statement that would break it fails, and its changes are undone.
Both sides of the relationship are protected. The child table (the one holding the foreign key) cannot point at a missing parent. The parent table (the one being referenced) cannot lose or change a row that children still point at.
The schema used here
CREATE TABLE customers (
customer_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
name VARCHAR(100) NOT NULL
);
CREATE TABLE orders (
order_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer_id INTEGER NOT NULL REFERENCES customers (customer_id),
ordered_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
INSERT INTO customers (email, name) VALUES ('[email protected]', 'Ana');
INSERT INTO orders (customer_id) VALUES (1);After these statements, customer 1 exists and has one order. No ON DELETE clause is given, so the default action, NO ACTION, applies.
The four ways to break the rule
Four kinds of statement can violate a foreign key. The table lists them with the side of the relationship each one touches.
| Statement | Table | Why it can fail |
|---|---|---|
| `INSERT` | child | The new row points at a parent that does not exist |
| `UPDATE` of the foreign key column | child | The new value points at a parent that does not exist |
| `DELETE` | parent | Child rows still reference the deleted row |
| `UPDATE` of the referenced key | parent | Child rows still reference the old value |
Deleting a child row never violates the rule, and neither does inserting a parent row. Those statements cannot create an orphan, which is a child row whose parent is missing.
Inserting a child with no parent
-- Fails: no customer with customer_id 999 exists
INSERT INTO orders (customer_id) VALUES (999);PostgreSQL rejects the statement with an error similar to this:
ERROR: insert or update on table "orders" violates foreign key constraint "orders_customer_id_fkey"
DETAIL: Key (customer_id)=(999) is not present in table "customers".The constraint name orders_customer_id_fkey was generated automatically because the table definition did not name it. The DETAIL line tells you which value was missing, which is the fastest clue when a bulk load fails.
Moving a child to a missing parent
An UPDATE is checked the same way as an INSERT:
-- Fails: customer 42 does not exist
UPDATE orders SET customer_id = 42 WHERE order_id = 1;The row stays as it was. Reassigning an order to a real customer succeeds, as long as that customer already exists.
Deleting a parent that has children
-- Fails while any order still references customer 1 (default NO ACTION)
DELETE FROM customers WHERE customer_id = 1;The error says the key is "still referenced from table orders". To remove the customer, you must first delete or reassign its orders, or declare a different referential action (the next chapter covers that choice).
Changing a referenced key
Updating the referenced value is rejected for the same reason. Because customer_id is a generated identity, you rarely change it, but the rule still applies to any parent key:
-- Fails: order 1 still points at customer_id 1
UPDATE customers SET customer_id = 500 WHERE customer_id = 1;Note that GENERATED ALWAYS identity columns also reject manual updates in PostgreSQL unless you use OVERRIDING SYSTEM VALUE in an insert. In that case you might see an identity error before the foreign key error. With a plain column, the foreign key error is the one you get.
NULL is allowed unless you forbid it
A foreign key check is skipped when the foreign key column is NULL. A NULL means "no parent", and there is nothing to match. That is why optional relationships work.
In the schema above, orders.customer_id is declared NOT NULL, so every order must have a customer. Without NOT NULL, this statement would succeed:
-- Succeeds only if customer_id is nullable
INSERT INTO orders (customer_id) VALUES (NULL);For a required relationship, the foreign key alone is not enough. You need both REFERENCES and NOT NULL.
Composite foreign keys and NULL
When a foreign key has several columns, NULL handling depends on the match type. With the default MATCH SIMPLE, the check is skipped if any column in the key is NULL. A row with (5, NULL) is accepted even if no parent has a key beginning with 5. MATCH FULL instead requires the columns to be all NULL or all non-NULL. Declare every column of a composite foreign key NOT NULL if you want the check to always run.
What the check does and does not cover
The following list shows the limits of the guarantee. These are the points where people assume more protection than they have.
- The foreign key must reference a column or column set that is a primary key or has a unique constraint. PostgreSQL refuses to create the constraint otherwise.
- The check compares values only. It does not know whether the parent row is "active", "approved", or otherwise meaningful to your application.
- Existing data is checked when you add a constraint to a populated table. If any child row is an orphan, the
ALTER TABLEfails. - The rule is enforced inside transactions. If a statement fails, the transaction is aborted in PostgreSQL, and you must roll back before running more statements.
- Truncating a referenced table is also blocked unless you truncate the child table in the same command or use
TRUNCATE ... CASCADE.
When the check happens
By default, PostgreSQL checks a NO ACTION foreign key at the end of the statement, not after each row. This matters for multi-row statements. Renumbering parent keys in a single UPDATE can succeed even if the intermediate state would have been invalid, as long as the final state is consistent. The RESTRICT action, by contrast, fails immediately and cannot be deferred. Deferred checks at commit time are possible with DEFERRABLE constraints, which a later chapter covers.
Reading and acting on the error
When a foreign key error appears, work through these steps.
- Read the constraint name and the
DETAILline to find the table and the value involved. - Decide which side failed. "is not present in table" means a child pointed at a missing parent. "is still referenced from table" means a parent has children.
- Query for the offending rows to confirm.
To find existing orphans before adding a constraint, use an anti-join:
SELECT o.order_id, o.customer_id
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;Any row returned is an orphan. Fix it by inserting the missing parent, pointing the row at a valid parent, or deleting it.
Exercise
A table invoices has customer_id INTEGER REFERENCES customers (customer_id) with no NOT NULL. A user runs INSERT INTO invoices (customer_id) VALUES (NULL);. Does it succeed, and what change would make the relationship required?
Show answer
It succeeds, because a foreign key check is skipped when the value is NULL. Adding NOT NULL to the customer_id column makes every invoice require a customer, and the foreign key then ensures that customer exists.
Exercise
Given customer 1 with one order, which of these fail under the default NO ACTION: (a) delete the order, (b) delete customer 1, (c) insert a new customer, (d) update the order's customer_id to 77 when no customer 77 exists?
Show answer
(b) and (d) fail. (b) leaves the order referencing a deleted parent. (d) points the child at a missing parent. (a) and (c) cannot create an orphan, so they succeed.