Skip to content

Instantly share code, notes, and snippets.

@kmoppel
Created April 14, 2020 10:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kmoppel/07b6a706de0d6cba990c192413e3d44b to your computer and use it in GitHub Desktop.
Save kmoppel/07b6a706de0d6cba990c192413e3d44b to your computer and use it in GitHub Desktop.
create unlogged table t(id serial primary key, parent_id int references t(id));
insert into t select i, case when i > 10 /* how many top level? */ then i::int / 10 else null end from generate_series(1, 1e4) i;
create index on t(parent_id);
vacuum analyze t;
with recursive q(id, level) as (
select 1 as id, 0 as level -- all descendants of top parent with id=1
union all
select t.id, q.level + 1 from q join t on t.parent_id = q.id
) select * from q;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment