Design a SQL query for Reddit-style hierarchical comment threads using a recursive CTE…
- User
Design a SQL query for Reddit-style hierarchical comment threads using a recursive CTE to fetch 5 levels deep, sorted by net score at each level. No OFFSET/LIMIT - and I need help optimizing it with the right composite index.
- Assistant
Designing recursive CTE for hierarchical comments
The recursive CTE fetches up to 5 comment levels per post, building a sort path as an array of negated net scores and IDs to order siblings by net score descending at each level. The recommended composite index on (post_id, parent_id, net_score DESC, id) optimizes the recursive join and sorting without OFFSET/LIMIT, supporting efficient hierarchical retrieval. Here is a straightforward way to do it in PostgreSQL with a recursive CTE. The idea is:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.