Skip to content

Instantly share code, notes, and snippets.

@alexesDev
Created August 13, 2018 12:35
Show Gist options
  • Save alexesDev/9ac33a7538a346af5005c65ae8401b1a to your computer and use it in GitHub Desktop.
Save alexesDev/9ac33a7538a346af5005c65ae8401b1a to your computer and use it in GitHub Desktop.
PostgreSQL: search a top-level root parent id
with recursive r as (
select id, parent_id
from products
where id = 100
union
select p.id, p.parent_id
from products p
join r on p.id = r.parent_id
)
select id from r where parent_id is null;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment