Find the Orphaned Rows
order.customer_id and order_item.order_id were
never declared as foreign keys. A migration is about to add both, and it will
fail on any row pointing at something that does not exist.
List those rows, from both tables, in one result set:
table_name—'order'or'order_item'row_id— the row's own idmissing_ref— the value it points at, which has no parent
Order by table_name, then row_id.
Report direct orphans only. An order_item whose
order_id does exist is not an orphan, even if that order
turns out to be one.
Expected output
table_name | row_id | missing_ref
-----------+--------+------------
order | 12 | 99
order_item | 102 | 999
Editorial
Two anti-joins, stacked:
SELECT 'order' AS table_name, o.id AS row_id, o.customer_id AS missing_ref
FROM "order" o
LEFT JOIN customer c ON c.id = o.customer_id
WHERE c.id IS NULL
UNION ALL
SELECT 'order_item', i.id, i.order_id
FROM order_item i
LEFT JOIN "order" o ON o.id = i.order_id
WHERE o.id IS NULL
ORDER BY table_name, row_id;
The anti-join idiom
LEFT JOIN then WHERE <right side> IS NULL.
The outer join keeps every child row; the filter keeps only the ones where the
join found nothing. It reads oddly the first few times — a WHERE
clause on the nullable side of an outer join normally destroys the
outer join, and here that is exactly the point.
Test the key column, not any column:
WHERE c.name IS NULL would also match a customer who exists with a
NULL name, reporting a row the migration will happily accept.
NOT EXISTS, which is the better default
SELECT 'order', o.id, o.customer_id
FROM "order" o
WHERE NOT EXISTS (SELECT 1 FROM customer c WHERE c.id = o.customer_id);
Same plan in PostgreSQL — the planner turns both into an anti-join — and
safer for two reasons. It cannot be broken by picking the wrong column to test
for NULL. And unlike NOT IN, it behaves correctly when the parent
key column contains NULLs: NOT IN against a subquery containing a
single NULL returns no rows at all, because the comparison chain
evaluates to unknown rather than true. Here customer.id is a
primary key so it cannot be NULL, which means NOT IN happens to
work — and "happens to work because of a constraint somewhere else" is a bad
thing to rely on in a cleanup script.
The transitive case
Item 101 points at order 12. Order 12 exists, so item 101 is not an orphan and the query correctly leaves it out. But order 12 is an orphan, so whatever the cleanup does about order 12 decides what happens to item 101:
- delete order 12, and item 101 becomes an orphan — the migration fails on the second constraint after you fixed the first
- repoint order 12 at a real customer, and item 101 is fine
Which is why the order the constraints are added in matters, and why the cleanup has to be re-run after each fix rather than computed once. The query answers "what blocks the migration right now", and "right now" moves every time you fix something.
To see the chain in one query:
SELECT i.id AS item, i.order_id, o.id IS NULL AS order_missing,
c.id IS NULL AS customer_missing
FROM order_item i
LEFT JOIN "order" o ON o.id = i.order_id
LEFT JOIN customer c ON c.id = o.customer_id;
Item 101 comes back with order_missing = false and
customer_missing = true, which is the row that needs a decision
rather than a delete.
UNION ALL, not UNION
UNION deduplicates, which means sorting or hashing the whole
result to remove duplicates that cannot exist — the two branches carry different
table_name literals, so no row from one can equal a row from the
other. UNION ALL skips that work. The habit worth forming is to
write UNION ALL by default and UNION only when you
have a reason to believe duplicates exist and want them gone.
Adding the constraints
Once the data is clean:
ALTER TABLE "order"
ADD CONSTRAINT order_customer_fk FOREIGN KEY (customer_id)
REFERENCES customer(id) NOT VALID;
ALTER TABLE "order" VALIDATE CONSTRAINT order_customer_fk;
NOT VALID adds the constraint so it applies to new and
changed rows immediately without checking the existing ones, which takes a
brief lock instead of a full table scan. VALIDATE then checks the
existing rows under a weaker lock that does not block reads or writes. On a
large table this two-step is the difference between a migration and an outage,
and it has a second benefit: the constraint starts protecting you from
new orphans while you are still cleaning up the old ones.
What an interviewer is checking
The anti-join, and then whether you ask what the orphans mean. The strong
answer does not jump to DELETE: an orphaned order is a real order
somebody was charged for, and the fix is usually to attach it to a placeholder
customer or restore the deleted one, not to destroy the evidence. The reason the
rows exist at all is the absent constraint, and the lasting fix is the
constraint plus ON DELETE RESTRICT, so the delete that created
them cannot happen again.
customer
2 rows
| idinteger | nametext |
|---|---|
| 1 | Acme |
| 2 | Begal |
order
4 rows
| idinteger | customer_idinteger | placed_ondate |
|---|---|---|
| 10 | 1 | 1704844800000000 |
| 11 | 2 | 1704931200000000 |
| 12 | 99 | 1705017600000000 |
| 13 | 1 | 1705104000000000 |
order_item
4 rows
| idinteger | order_idinteger | skutext |
|---|---|---|
| 100 | 10 | SKU-A |
| 101 | 12 | SKU-B |
| 102 | 999 | SKU-C |
| 103 | 13 | SKU-D |