A recursive CTE allows you to perform recursion within a query using the WITH RECURSIVEsyntax. Use a recursive query to deal with hierarchical or nested data structures such as trees or graphs.
WITH RECURSIVE cte_name (column1, column2, ...)
AS(
-- anchor member
SELECT select_list FROM table1 WHERE condition
UNION [ALL]
-- recursive member
SELECT select_list FROM cte_name WHERE recursive_condition
)
SELECT * FROM cte_name;
How PostgreSQL executes:
Practice: