Skip to content

Instantly share code, notes, and snippets.

@robinhouston
Created October 6, 2019 17:10
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robinhouston/f689a4b833dc027a3fd97e3de855927b to your computer and use it in GitHub Desktop.
Save robinhouston/f689a4b833dc027a3fd97e3de855927b to your computer and use it in GitHub Desktop.
create table tweet (
id serial,
in_reply_to integer references tweet(id)
);
insert into tweet (id, in_reply_to)
values (1, NULL),
(2, NULL),
(3, 2),
(4, 3),
(5, 3),
(6, 5);
with recursive thread as (
select id, in_reply_to, 0 as depth
from tweet
where in_reply_to is null
union
select tweet.id
, tweet.in_reply_to
, 1 + thread.depth as depth
from thread
join tweet on tweet.in_reply_to = thread.id
)
select id from thread
where depth = (
select max(depth) from thread
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment