Given a table (simplified):

CREATE TABLE tree ( id INTEGER NOT NULL, node_id INTEGER, parent INTEGER ) 

Where node_id is id of the node, and parent is id of parent node. Root node has id=0.

How to find all "leaf" nodes, i.e. all nodes that is not a parent for any else node?

0

2 Answers

Try a LEFT self JOIN and check for NULL values:

SELECT leaf.node_id FROM tree AS leaf LEFT OUTER JOIN tree AS child on child.parent = leaf.node_id WHERE child.node_id IS NULL 

I would use not exists:

select t.* from t where not exists (select 1 from tree t2 where t2.parent = t.node_id); 

This is pretty equivalent to the left join method. I just think that not exists is clearer about the intent of the query.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.