// SQL snippet

Find missing parent references, both ways

Check a parent-child pair in both directions at once: children whose parent id is NULL or dangling, and parents that no child references.

Main statement
All engines

The task

You inherited a schema where orders.customer_id is optional and suspect both problems at once: orders with a broken or missing customer link, and customers nobody ever ordered from. One labeled result set beats running two queries.

The snippet

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

All engines
SELECT 'child: order with no customer' AS issue,
       o.id AS row_id, o.customer_id AS related_id
FROM orders o
LEFT JOIN customers c ON c.id = o.customer_id
WHERE c.id IS NULL
UNION ALL
SELECT 'parent: customer without orders',
       c.id, NULL
FROM customers c
WHERE NOT EXISTS (
  SELECT 1 FROM orders o WHERE o.customer_id = c.id
)
ORDER BY issue, row_id;

So funktioniert es

The first branch catches orders where the join to customers found nothing, which includes both NULL customer_ids and dangling ids, since neither can match a parent. The second branch uses NOT EXISTS to find parents that no child references. The literal label column lets you tell the two directions apart after the UNION ALL merges them.

Variations

Separate NULL and dangling child refs

SELECT 'order with NULL customer_id' AS issue, o.id AS row_id
FROM orders o
WHERE o.customer_id IS NULL
UNION ALL
SELECT 'order with dangling customer_id', o.id
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;

Questions that come up

Is a parent with no children always a problem?

Not necessarily. A customer who has not ordered yet is normal in many schemas. Treat the parent branch as a candidate list for cleanup, not a defect list. The child branch, on the other hand, is usually a real integrity violation worth fixing before it grows.

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.