// SQL snippet

Audit all foreign keys in both directions

Stack a LEFT JOIN anti-join per foreign key with UNION ALL to get an orphan count for every relationship in one query.

Main statement
All engines

The task

Before trusting a vendor database, run one integrity sweep: for each FK relationship, how many child rows point at a missing parent? The labeled output doubles as documentation of the schema's relationships.

The snippet

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

All engines
SELECT 'orders.customer_id -> customers.id' AS relationship,
       COUNT(*) AS orphaned_rows
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
UNION ALL
SELECT 'order_items.order_id -> orders.id', COUNT(*)
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
ORDER BY orphaned_rows DESC;

Cómo funciona

Each branch is the orphan check for one relationship: LEFT JOIN the parent, keep rows the join could not satisfy, and COUNT them under a descriptive label. UNION ALL stacks the cheap counts into one report. ORDER BY puts the most damaged relationship on top; a clean schema returns all zeros.

Variations

Add childless-parent counts to the audit

SELECT 'customers with no orders' AS relationship, COUNT(*) AS row_count
FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id)
UNION ALL
SELECT 'orders with no items', COUNT(*)
FROM orders o
WHERE NOT EXISTS (SELECT 1 FROM order_items oi WHERE oi.order_id = o.id);

Questions that come up

Why label with column -> column strings?

The labels are free text, so this report reads the same for a developer and a stakeholder, and each row names the exact join to write when fixing the orphans. Keep one branch per declared or planned foreign key and the query becomes an integrity checklist you can rerun after every import.

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.