Find rows orphaned from their parent
When a parent row is deleted without cleaning up its children, the children become orphans. A LEFT JOIN against the parent with an IS NULL test finds every one of them.
The task
orders.customer_id should always point at a customers row, but manual deletes and broken imports have left orders whose customer no longer exists. You need the list before you reassign or remove those orders.
The snippet
Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.
SELECT o.id AS order_id, o.customer_id, o.order_date, o.total
FROM orders o
LEFT JOIN customers c ON c.id = o.customer_id
WHERE o.customer_id IS NOT NULL
AND c.id IS NULL;
Cómo funciona
The LEFT JOIN keeps every order and carries NULLs for the ones whose customer is gone. The first WHERE condition ignores orders that deliberately have no customer; the second keeps only orders whose lookup found no parent. A NOT EXISTS variant is equivalent and sometimes reads better.
Variations
NOT EXISTS form
SELECT o.id AS order_id, o.customer_id
FROM orders o
WHERE o.customer_id IS NOT NULL
AND NOT EXISTS (
SELECT 1 FROM customers c WHERE c.id = o.customer_id
);
Count orphans per missing parent id
SELECT o.customer_id, COUNT(*) AS orphaned_orders
FROM orders o
LEFT JOIN customers c ON c.id = o.customer_id
WHERE o.customer_id IS NOT NULL AND c.id IS NULL
GROUP BY o.customer_id
ORDER BY orphaned_orders DESC;
Questions that come up
Why exclude o.customer_id IS NULL?
A NULL customer_id means 'no parent on purpose', which is not an orphan: the row simply has no relationship. Filtering it out leaves only rows that claim a parent the parent table cannot find. Drop the condition if NULLs in this column are themselves a rule violation in your schema.
Keep reading
Run these with autocomplete that knows your tables
SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.