Sub topic 8
What Referential Integrity Rejects
This chapter assumes you can create tables and use basic SELECT, INSERT, UPDATE, and DELETE statements. The examples use PostgreSQL-style SQL.
Referential integrity is the rule that keeps a foreign key relationship valid. A foreign key value must either match an existing key in the referenced table or, when the column allows it, be NULL. The database checks this rule when rows are inserted, updated, or deleted.
Missing parent rows
Suppose orders.customer_id references customers.customer_id:
CREATE TABLE customers (
customer_id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
CREATE TABLE orders (
order_id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL
REFERENCES customers (customer_id)
);
INSERT INTO customers (customer_id, name)
VALUES (1, 'Mina');
INSERT INTO orders (order_id, customer_id)
VALUES (101, 1);The order is valid because customer 1 exists. This insert is rejected:
INSERT INTO orders (order_id, customer_id)
VALUES (102, 999);No customer has ID 999, so the foreign key would point to a missing parent row.
An update is checked in the same way:
UPDATE orders
SET customer_id = 999
WHERE order_id = 101;The database rejects the update because it would create an invalid reference.
Deleting or changing a referenced parent
The reverse operation can also violate integrity. If an order still references customer 1, this statement is normally rejected:
DELETE FROM customers
WHERE customer_id = 1;Deleting the customer would leave order 101 with no valid parent. Changing the referenced key can cause the same problem:
UPDATE customers
SET customer_id = 7
WHERE customer_id = 1;The default behavior, usually called NO ACTION, checks whether dependent rows would become invalid. The exact timing can differ for deferred constraints, but the invalid final state is rejected.
| Operation | Result when it breaks the reference |
|---|---|
| Insert child with missing parent | Rejected |
| Update child to missing parent | Rejected |
| Delete referenced parent | Rejected by default |
| Update referenced parent key | Rejected by default |
A useful mental model
A nullable foreign key is different. If customer_id permits NULL, an order with customer_id = NULL represents no known customer and does not require a matching parent. NULL is not the same as an invalid value such as 999.
Exercise
A customer has two orders. What happens when you delete that customer under the default foreign key behavior?
Show answer
The delete is rejected because the orders would become orphaned. You must first remove or change the orders, or define an appropriate referential action such as ON DELETE CASCADE or ON DELETE SET NULL.