Need SQL Query to find Parent records without child records

With another example as

Enumerate table

    id: SERIAL
    name: TEXT
    enumerate_id: INT

All parents who have children (all branches of a tree, even roots, but no leaf!)

SELECT id, name, enumerate_id
FROM enumerate p
WHERE EXISTS (
    SELECT 1 FROM enumerate c
    WHERE c.enumerate_id = p.id
);

All children who don't have children (all leafs of a tree)

SELECT id, name, enumerate_id
FROM enumerate p
WHERE NOT EXISTS (
    SELECT 1 FROM enumerate c
    WHERE c.enumerate_id = p.id
);

Note that the only one who changes is the NOT EXISTS

Hope it helps


If you do a left join on the child table and simply say where the child parentID is null.

SELECT ParentTable.ParentID FROM ParentTable P
    Left Join ChildTable C on C.ParentID = P.ParentID
    WHERE C.Id IS NULL;

Outer join parent to child, and then having count(*) = 0.

select
  p.parent_id,
  count(*)
from
  parent p left outer join child c on p.parent_id = c.parent_id
group by
  p.parent_id
having
  count(*) = 0

You can use a NOT EXISTS clause for this

SELECT ParentTable.ParentID
FROM ParentTable
WHERE NOT EXISTS (
    SELECT 1 FROM ChildTable
    WHERE ChildTable.ParentID = ParentTable.ParentID
)

There's also the old left join and check for null approach

SELECT ParentTable.ParentID
FROM ParentTable
LEFT JOIN ChildTable
  ON ParentTable.ParentID = ChildTable.ParentID
WHERE ChildTable.ChildID IS NULL

Try both and see which one works better for you.

Tags:

Sql