Hierarchical parent query in postgres Hierarchical parent query in postgres database database

Hierarchical parent query in postgres


CTEs in PostgreSQL are fenced meaning they will be materialized and only then will the filter from outer query will be applied. To make the query perform correctly build it the other way around and put the filter inside the CTE.

WITH RECURSIVE the_somethings(id_something, path) AS (SELECT id_something, id_something::TEXT as path, 0 as level, id_something AS orig_idFROM something_tableWHERE id_something IN ($id_to_start_with,$id_to_start_with2)UNION ALLSELECT D.id_something, (D.id_something::TEXT || ',' || DR.path) as path, DR.level + 1, DR.orig_idFROM something_table DJOIN the_somethings DR ON DR.id_something_parent = D.id_something)SELECT DISTINCT ON(orig_id) orig_id, pathFROM the_somethingsORDER BY orig_id, DR.level DESC