How would you find orphan records or missing relationships with SQL?
Answer
Use a LEFT JOIN from the child to the parent and filter where the parent key is NULL, or use NOT EXISTS with a correlated subquery. Confirm whether a nullable foreign key is valid before treating every missing relationship as a defect. Compare the query with declared foreign-key rules, soft deletes, effective dates and ingestion order so that legitimate temporary states are not misclassified as broken integrity.
Strong answer includes
- uses LEFT JOIN or NOT EXISTS correctly
- distinguishes valid null relationships from orphans
- checks constraints, soft deletes and timing
Practical example
Dialect · Portable SQLRuntime · SQLite sample DB
Runs against the resettable SQLite sample database used by the playground.
SQL
Result
Run the query to see the result.
The child row is kept only when no matching parent exists. The explicit customer_id IS NOT NULL condition avoids treating a deliberately nullable relationship as an orphan.
Expected result: Zero rows when referential integrity is intact.