// SQL snippet

Orphan sweep across multiple parents

One branch per foreign key, each an anti-join; UNION ALL merges them into a labeled list of every dangling reference in the table.

Main statement
All engines

The task

order_items points at both orders and products. A deleted order orphans lines just as surely as a deleted product, so the sweep checks every foreign key of the table and names which one broke.

The snippet

Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.

All engines
SELECT 'order_items.order_id -> orders.id' AS broken_reference,
       oi.order_id AS missing_value
FROM order_items oi
LEFT JOIN orders o ON o.id = oi.order_id
WHERE oi.order_id IS NOT NULL AND o.id IS NULL
UNION ALL
SELECT 'order_items.product_id -> products.id',
       pi.product_id
FROM order_items pi
LEFT JOIN products p ON p.id = pi.product_id
WHERE pi.product_id IS NOT NULL AND p.id IS NULL
ORDER BY broken_reference, missing_value;

Como funciona

Each branch is the standard orphan anti-join for one foreign key, labeled with the relationship it inspects. The IS NOT NULL test matters: a NULL foreign key never matches a parent, so without it every line with no product would be reported as an orphan. The ORDER BY groups the report by relationship, so fixing one FK means working one block.

Variations

Counts per relationship instead of values

SELECT 'order_items.order_id -> orders.id' AS broken_reference,
       COUNT(*) AS orphaned_rows
FROM order_items oi
LEFT JOIN orders o ON o.id = oi.order_id
WHERE oi.order_id IS NOT NULL AND o.id IS NULL
UNION ALL
SELECT 'order_items.product_id -> products.id', COUNT(*)
FROM order_items pi
LEFT JOIN products p ON p.id = pi.product_id
WHERE pi.product_id IS NOT NULL AND p.id IS NULL;

Questions that come up

Sweep or full audit: which one when?

The sweep inspects one child table against all its parents; the full audit walks every relationship in the schema. Run the audit on schema changes and after imports, the sweep while investigating a specific table. They share the same anti-join shape, so moving between them is copy, relabel and regroup.

Keep reading

// snippets are better with a schema brain

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.