Skip to content
Advertisement

SELECT Records From Child Table That Are Not In Another And Parent Has No Other Children

I’m trying to write a query to select all orphan records that are in a child table, but only when orphaned records are the only items in the table.

I have two separate databases from separate systems, and so I cannot enforce referential integrity constraints using foreign keys. A simple schema of each is below:

Using the above data as an example, I’d want a query that returns Order 2 because the only item(s) available on the parent have been deleted.

So far, I have the below query that returns for me all records that are orphaned, including order 1.

Any ideas?

Advertisement

Answer

Your query is almost there:

this query finds all orders where every c.Item related to the order is null

after left joining your data looks like:

grouping and counting c.Item gives;

because count counts up, a step of 0 for nulls and increment of 1 for any non null

and we want the i.Order=2 row which is what HAVING gives us; HAVING is a where clause that is applied after grouping is done. (WHERE clauses are applied before grouping and cannot be used for this)

hence this query finds every order where ALL of its c.Items are NULL

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement