Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
QA interview question
Databases, SQL & BISQL languageJuniorCommonPractical

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

Find child rows whose parent is missing
Dialect · Portable SQLRuntime · SQLite sample DB

Runs against the resettable SQLite sample database used by the playground.

SQL
SQLite · sample DB · browser sandbox
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.

#sql#database#referential-integrity#joins

Sources

PostgreSQL documentationPostgreSQL Global Development Group · Relational modelling, SQL, joins, constraints, transactions, concurrency, indexes, query plans and recoveryAdd data tests to your DAGdbt Labs · Reusable assertions for analytics transformations and data contracts