Sub topic 13
Optional Relationships and NULL Foreign Keys
This chapter assumes you can write CREATE TABLE, INSERT, SELECT and basic joins. It also assumes you know what a primary key and a foreign key are, and how NULL behaves in comparisons. The chapter is about foreign key columns that are allowed to be NULL, and the effects that has on constraints, joins, and counts.
Mandatory versus optional relationships
A foreign key column links a child row to a parent row. Whether every child row must have a parent depends on one thing: the NOT NULL constraint on the foreign key column.
- With
NOT NULL, the relationship is mandatory. Every row must point to an existing parent. - Without
NOT NULL, the relationship is optional. A row may point to a parent, or it may point to nothing.
In the orders table from earlier chapters, customer_id is NOT NULL, so an order cannot exist without a customer. Consider a different case: a support ticket that may or may not be assigned to an agent.
CREATE TABLE agents (
agent_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
CREATE TABLE tickets (
ticket_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title VARCHAR(200) NOT NULL,
assigned_to INTEGER REFERENCES agents (agent_id) ON DELETE SET NULL
);assigned_to has no NOT NULL, so a new ticket can start unassigned. A NULL value means "no agent yet", not "an agent we cannot identify".
How the database checks a NULL foreign key
A foreign key constraint only checks rows whose foreign key value is not NULL. A NULL passes automatically, because it does not claim to reference anything.
INSERT INTO agents (name) VALUES ('Priya');
-- Succeeds: references an existing agent
INSERT INTO tickets (title, assigned_to) VALUES ('Printer jam', 1);
-- Succeeds: NULL means unassigned, so there is nothing to check
INSERT INTO tickets (title, assigned_to) VALUES ('Password reset', NULL);
-- Fails: agent 42 does not exist
INSERT INTO tickets (title, assigned_to) VALUES ('VPN down', 42);Only the third insert violates the constraint. The rule is "either NULL, or a value that exists in the parent".
Using SET NULL with optional relationships
ON DELETE SET NULL is a natural fit for optional relationships. When a parent row is deleted, the database sets the child's foreign key to NULL instead of rejecting the delete or deleting the child.
DELETE FROM agents WHERE agent_id = 1;
SELECT ticket_id, title, assigned_to FROM tickets;The "Printer jam" ticket survives, and its assigned_to is now NULL. The ticket returns to the unassigned pool.
SET NULL only works if the column accepts NULL. If you declare NOT NULL together with ON DELETE SET NULL, PostgreSQL accepts the table definition. The first delete that triggers the action then fails with a not-null violation. Treat that combination as a design error.
| Foreign key column | ON DELETE action | Result when the parent is deleted |
|---|---|---|
| Nullable | SET NULL | Child row stays, column becomes NULL |
| Nullable | CASCADE | Child rows are deleted |
| NOT NULL | RESTRICT or NO ACTION | Delete is rejected while children exist |
| NOT NULL | SET NULL | Delete fails with a not-null error |
Querying optional relationships
NULL foreign keys change how joins behave. An inner join drops rows that have no parent, so unassigned tickets disappear.
-- Only tickets that have an agent
SELECT t.title, a.name
FROM tickets AS t
JOIN agents AS a ON a.agent_id = t.assigned_to;To keep every ticket, use a LEFT JOIN. Unassigned tickets get NULL in the agent columns.
SELECT t.title, COALESCE(a.name, 'Unassigned') AS agent
FROM tickets AS t
LEFT JOIN agents AS a ON a.agent_id = t.assigned_to
ORDER BY t.ticket_id;The join condition a.agent_id = t.assigned_to evaluates to unknown, not true, when assigned_to is NULL. That is why the inner join drops the row, and why the left join fills in NULLs.
To find rows that lack a relationship, test with IS NULL. Do not use = NULL, which never matches.
-- Unassigned tickets
SELECT ticket_id, title FROM tickets WHERE assigned_to IS NULL;
-- Agents with no tickets (an anti-join)
SELECT a.agent_id, a.name
FROM agents AS a
LEFT JOIN tickets AS t ON t.assigned_to = a.agent_id
WHERE t.ticket_id IS NULL;In the anti-join, the WHERE test uses the child's primary key. That column is never NULL in a real row, so a NULL there can only come from a missing match.
Gotchas with NULL foreign keys
- Counting.
COUNT(assigned_to)ignores NULLs, whileCOUNT(*)counts every row. The two numbers differ by the number of unassigned tickets. - Uniqueness. In PostgreSQL, a
UNIQUEconstraint allows multiple NULLs. A nullable, unique foreign key therefore permits many unassigned rows but only one row per real parent. This is a common way to model an optional one-to-one relationship. SQL Server treats NULLs in a unique constraint as equal, so it allows only one NULL. Check your database's rules. - NOT IN.
WHERE assigned_to NOT IN (SELECT agent_id FROM agents)returns nothing if the subquery produces any NULL. UseNOT EXISTSwhen NULLs are possible. - Hidden business rules. A nullable column can mean several things: not assigned yet, not applicable, or unknown. If the distinction matters, add a status column rather than overloading NULL.
Choosing mandatory or optional
Start from the business rule. If a child row has no meaning without its parent, such as an order line without an order, make the column NOT NULL. If the parent is assigned later or can be removed without invalidating the child, allow NULL and pair it with ON DELETE SET NULL.
Prefer NOT NULL when in doubt. A mandatory relationship gives the database more to enforce, and you can relax it later with ALTER TABLE ... ALTER COLUMN ... DROP NOT NULL. Tightening it later requires first fixing every existing NULL row.
Exercise
A table tickets has assigned_to INTEGER REFERENCES agents (agent_id), with no NOT NULL. It holds 10 rows, 3 of which have assigned_to NULL. What do SELECT COUNT(*), SELECT COUNT(assigned_to), and an inner join of tickets to agents on agent_id = assigned_to return, assuming every non-NULL value matches an agent?
Show answer
COUNT(*) returns 10, because it counts rows. COUNT(assigned_to) returns 7, because it skips NULLs. The inner join returns 7 rows, because NULL = anything is unknown, so the 3 unassigned tickets are dropped. A LEFT JOIN would return all 10.
Exercise
You define agent_id INTEGER NOT NULL REFERENCES agents (agent_id) ON DELETE SET NULL. What happens when you delete an agent who has tickets?
Show answer
The table is created successfully, but the delete fails with a not-null violation, because SET NULL tries to write NULL into a NOT NULL column. Either remove NOT NULL or choose a different action such as RESTRICT.