Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collect all leaf nodes with Postgres ltree

I have been using Postgres ltree construct to store a hierarchical structure. Now, I want to collect all the leaf nodes in the tree. Is there a straightforward mechanism to do this?

CREATE TABLE foo
AS
  SELECT node::ltree
  FROM ( VALUES
    ('Top.Astronomy'),
    ('Top.Astronomy.Astrophysics'),
    ('Top.Pictures'),
    ('Top.Pictures.Stars')
  ) AS t(node);

How do I return

Top.Astronomy.Astrophysics
Top.Pictures.Stars
like image 364
Phelodas Avatar asked May 16 '26 19:05

Phelodas


1 Answers

Using @>

One way is to use the contains operator @>

SELECT *
FROM foo AS f1
WHERE NOT EXISTS (
  SELECT *
  FROM foo AS f2
  WHERE f1.node @> f2.node
    AND f1.node <> f2.node
);
            node            
----------------------------
 Top.Astronomy.Astrophysics
 Top.Pictures.Stars
(2 rows)
like image 114
NO WAR WITH RUSSIA Avatar answered May 20 '26 17:05

NO WAR WITH RUSSIA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!