Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Worked example · 25 min · revision 2

Readable Step-by-Step Queries with CTEs and Recursion

A worked example on a shop category tree in PostgreSQL 17: untangle a nested query into named CTE steps, see when the planner inlines a CTE, walk the tree with a recursive CTE, roll revenue up to every ancestor and stop a cycle in bad data.

Contentsand lesson path

What you will learn

  • Structure multi-step logic with CTEs, including a recursive CTE that walks hierarchical data.

Prerequisites: SQL Fundamentals

01. The problem

An online shop sorts its products into a category tree: Home contains Kitchen and Garden, Kitchen contains Knives and Pans, and so on. Each category row stores only its parent_id, the category directly above it. Products belong to the lowest categories. The merchandising team asks for three things:

  1. the categories that bring in at least 10 % of all revenue;
  2. the whole tree, with a breadcrumb path such as "Home > Kitchen > Knives";
  3. revenue for every category including everything below it, so that Home shows the sum of Kitchen and Garden.

Request 1 is hard to read as nested subqueries. Requests 2 and 3 need to follow parent_id links to an unknown depth, which no fixed number of joins can do. A common table expression (CTE) solves the first; a recursive CTE solves the others. You will also make the query survive a data error that turns the tree into a loop.

The example uses PostgreSQL 17 in the sql-lab container from the window functions lesson. Save the script as tree.sql and load it into a new database.

SQL · tree.sql
CREATE TABLE categories (
  id        int PRIMARY KEY,
  parent_id int REFERENCES categories,
  name      text NOT NULL
);
INSERT INTO categories VALUES
  (1, NULL, 'Home'),  (2, 1, 'Kitchen'), (3, 2, 'Knives'), (4, 2, 'Pans'),
  (5, 1, 'Garden'),   (6, 5, 'Tools'),
  (7, NULL, 'Sport'), (8, 7, 'Running'), (9, 8, 'Shoes'),  (10, 7, 'Cycling');
CREATE TABLE products (
  product_id  int PRIMARY KEY,
  name        text NOT NULL,
  category_id int NOT NULL REFERENCES categories
);
INSERT INTO products VALUES
  (101, 'Chef knife', 3), (102, 'Paring knife', 3), (103, 'Frying pan', 4),
  (104, 'Spade', 6), (105, 'Trail shoe', 9), (106, 'Bike light', 10);
CREATE TABLE order_lines (
  order_id   int NOT NULL,
  product_id int NOT NULL REFERENCES products,
  qty        int NOT NULL,
  unit_price numeric(8,2) NOT NULL
);
INSERT INTO order_lines VALUES
  (1, 101, 1, 80), (1, 103, 1, 45), (2, 102, 2, 15), (3, 104, 1, 30),
  (4, 105, 1, 120), (4, 106, 2, 20), (5, 101, 1, 80), (6, 105, 1, 120);
SELECT (SELECT count(*) FROM categories) AS categories,
       (SELECT count(*) FROM products) AS products,
       (SELECT count(*) FROM order_lines) AS order_lines;
Terminal
docker exec sql-lab psql -U postgres -X -q -c "SET client_min_messages = warning" \
  -c "DROP DATABASE IF EXISTS tree" -c "CREATE DATABASE tree"
docker exec -i sql-lab psql -U postgres -d tree -X -q < tree.sql
Expected output
 categories | products | order_lines 
------------+----------+-------------
         10 |        6 |           8
(1 row)

02. Step 1: Untangle a nested query into named steps

Here is a first answer to request 1, written the way queries often grow: a subquery in FROM, and the grand total computed twice in scalar subqueries.

SQL · psql, database tree
SELECT c.name, r.revenue,
       round(100 * r.revenue / (SELECT sum(qty * unit_price) FROM order_lines), 1)
         AS pct
FROM (SELECT p.category_id, sum(ol.qty * ol.unit_price) AS revenue
      FROM order_lines ol JOIN products p ON p.product_id = ol.product_id
      GROUP BY p.category_id) AS r
JOIN categories c ON c.id = r.category_id
WHERE r.revenue >= 0.1 * (SELECT sum(qty * unit_price) FROM order_lines)
ORDER BY r.revenue DESC;
Expected output
  name  | revenue | pct  
--------+---------+------
 Shoes  |  240.00 | 44.0
 Knives |  190.00 | 34.9
(2 rows)

The answer is right, but the logic reads inside out, and the 10 % rule and the percentage use two copies of the same total that can drift apart when someone edits one. A CTE, written WITH name AS (query), gives a subquery a name so later parts of the statement can use it like a table. Rewrite the query as a chain where each CTE does one thing: line_revenue prices each order line, category_revenue sums per category, and shares adds the percentage with a window function over the whole result (OVER ()). The final SELECT only filters and sorts.

SQL · psql, database tree
WITH line_revenue AS (
  SELECT p.category_id, ol.qty * ol.unit_price AS revenue
  FROM order_lines ol JOIN products p ON p.product_id = ol.product_id
), category_revenue AS (
  SELECT category_id, sum(revenue) AS revenue
  FROM line_revenue GROUP BY category_id
), shares AS (
  SELECT c.name, cr.revenue,
         round(100 * cr.revenue / sum(cr.revenue) OVER (), 1) AS pct
  FROM category_revenue cr JOIN categories c ON c.id = cr.category_id
)
SELECT name, revenue, pct FROM shares WHERE pct >= 10 ORDER BY revenue DESC;
Expected output
  name  | revenue | pct  
--------+---------+------
 Shoes  |  240.00 | 44.0
 Knives |  190.00 | 34.9
(2 rows)

Same result, and now each step has a name you can read aloud. The chain is also easy to debug: replace the final SELECT with SELECT * FROM category_revenue; and you see exactly what that step produces. When a long query returns too few rows, checking each step this way finds the one that loses them. Name each CTE after what its rows are, not step2.

03. Step 2: Know when PostgreSQL inlines a CTE

A common belief is that a CTE is always computed first and stored, like a temporary table. That was true before PostgreSQL 12. Since version 12, a CTE that is not recursive, has no side effects and is referenced only once is inlined: the planner merges it into the outer query and can push filters into it. A CTE referenced twice or more is computed once and reused, which is called materialised. You can override the choice with AS MATERIALIZED or AS NOT MATERIALIZED. EXPLAIN (COSTS OFF) prints the plan without the cost numbers, so you can compare the two forms.

SQL · psql, database tree
EXPLAIN (COSTS OFF)
WITH named AS (SELECT * FROM categories)
SELECT name FROM named WHERE id = 3;

EXPLAIN (COSTS OFF)
WITH named AS MATERIALIZED (SELECT * FROM categories)
SELECT name FROM named WHERE id = 3;
Expected output
                   QUERY PLAN                   
------------------------------------------------
 Index Scan using categories_pkey on categories
   Index Cond: (id = 3)
(2 rows)

           QUERY PLAN           
--------------------------------
 CTE Scan on named
   Filter: (id = 3)
   CTE named
     ->  Seq Scan on categories
(4 rows)

In the first plan the CTE has vanished: the filter id = 3 reached the table and the primary-key index answers it. In the second plan PostgreSQL scans the whole table into the CTE, then filters the stored rows (CTE Scan). On ten rows it makes no difference; on a large table it can, so check the plan rather than assume. MATERIALIZED is useful when a CTE is expensive and you want it computed exactly once, or as a deliberate barrier when the planner chooses badly.

04. Step 3: Walk the tree with a recursive CTE

A recursive CTE has two parts joined by UNION ALL. The anchor (non-recursive term) produces the starting rows: here, the root categories, whose parent_id is NULL. The recursive term refers to the CTE itself and produces the next level from the previous one. PostgreSQL evaluates it in rounds. It runs the anchor and puts the result in a working table. Each round runs the recursive term against the working table only, that is, the rows found in the previous round, and those new rows become the next working table. When a round produces no rows, the recursion stops, and the result is everything produced in all rounds.

To walk down, join each category to the rows already found through its parent_id: "give me the children of what I have". Carry two extra columns as you go: depth, one more than the parent's, and path, the parent's path plus this name.

SQL · psql, database tree
WITH RECURSIVE tree AS (
  SELECT id, name, 1 AS depth, name AS path
  FROM categories WHERE parent_id IS NULL
  UNION ALL
  SELECT c.id, c.name, t.depth + 1, t.path || ' > ' || c.name
  FROM categories c JOIN tree t ON c.parent_id = t.id
)
SELECT id, depth, path FROM tree ORDER BY path;
Expected output
 id | depth |          path           
----+-------+-------------------------
  1 |     1 | Home
  5 |     2 | Home > Garden
  6 |     3 | Home > Garden > Tools
  2 |     2 | Home > Kitchen
  3 |     3 | Home > Kitchen > Knives
  4 |     3 | Home > Kitchen > Pans
  7 |     1 | Sport
 10 |     2 | Sport > Cycling
  8 |     2 | Sport > Running
  9 |     3 | Sport > Running > Shoes
(10 rows)

Round 1 (the anchor) found Home and Sport. Round 2 found their children: Kitchen, Garden, Running and Cycling. Round 3 found Knives, Pans, Tools and Shoes. Round 4 found no children of those, so it stopped. The anchor and the recursive term must return the same number of columns with compatible types; if the anchor column were varchar(20) and the recursive one text, PostgreSQL would refuse the query until you cast one of them.

05. Step 4: Print the tree in depth-first order

Sorting by the path text works here, but it is fragile: a root named "Home & Garden" sorts between "Home" and "Home > Garden", in the middle of another branch. PostgreSQL 14 added the standard SEARCH clause, which computes a sort column for you. SEARCH DEPTH FIRST BY name SET ord visits each branch fully before the next, ordering siblings by name; SEARCH BREADTH FIRST would list level by level instead. Indenting by depth with repeat makes the shape visible.

SQL · psql, database tree
WITH RECURSIVE tree AS (
  SELECT id, name, 1 AS depth FROM categories WHERE parent_id IS NULL
  UNION ALL
  SELECT c.id, c.name, t.depth + 1
  FROM categories c JOIN tree t ON c.parent_id = t.id
) SEARCH DEPTH FIRST BY name SET ord
SELECT repeat('  ', depth - 1) || name AS category FROM tree ORDER BY ord;
Expected output
  category  
------------
 Home
   Garden
     Tools
   Kitchen
     Knives
     Pans
 Sport
   Cycling
   Running
     Shoes
(10 rows)

06. Step 5: Roll revenue up to every ancestor

Request 3 needs, for every category, the set of categories at or below it. Build that as pairs. The anchor pairs every category with itself; the recursive term extends each pair one level down, keeping the same ancestor. The result is a closure: one row (ancestor, descendant) for every pair connected by a downward path, including each category with itself. Join product revenue on the descendant and group by the ancestor. LEFT JOIN and coalesce keep categories without sales at zero.

SQL · psql, database tree
WITH RECURSIVE sub AS (
  SELECT id AS ancestor_id, id AS category_id FROM categories
  UNION ALL
  SELECT s.ancestor_id, c.id
  FROM sub s JOIN categories c ON c.parent_id = s.category_id
), category_revenue AS (
  SELECT p.category_id, sum(ol.qty * ol.unit_price) AS revenue
  FROM order_lines ol JOIN products p ON p.product_id = ol.product_id
  GROUP BY p.category_id
)
SELECT a.name, coalesce(sum(cr.revenue), 0) AS revenue_incl_children
FROM sub s
JOIN categories a ON a.id = s.ancestor_id
LEFT JOIN category_revenue cr ON cr.category_id = s.category_id
GROUP BY a.id, a.name
ORDER BY a.id;
Expected output
  name   | revenue_incl_children 
---------+-----------------------
 Home    |                265.00
 Kitchen |                235.00
 Knives  |                190.00
 Pans    |                 45.00
 Garden  |                 30.00
 Tools   |                 30.00
 Sport   |                280.00
 Running |                240.00
 Shoes   |                240.00
 Cycling |                 40.00
(10 rows)

Check Home: Knives 190 + Pans 45 + Tools 30 = 265. Kitchen and Garden have no products of their own, yet they show revenue, because their descendants do. Notice that WITH RECURSIVE applies to the whole WITH list: the second CTE, category_revenue, is an ordinary one.

07. Step 6: Stop a cycle in bad data

A recursive CTE stops only when a round returns no rows. If an import error sets Home's parent to Knives, the data contains a loop, Kitchen → Knives → Home → Kitchen, and a walk that enters it never ends. PostgreSQL has no built-in limit, so the query runs until you cancel it, a statement_timeout stops it, or its temporary files fill the disk. Run the experiment in a transaction that you roll back. The first query uses the CYCLE clause (PostgreSQL 14 and later): CYCLE id SET is_cycle USING visited tracks the ids seen on each path and marks the row that repeats one instead of extending it. The second query does the same by hand with an array of visited ids, which also works in older versions and other databases.

SQL · psql, database tree
BEGIN;
UPDATE categories SET parent_id = 3 WHERE id = 1;  -- bad import: Home under Knives

WITH RECURSIVE walk AS (
  SELECT id, name, 0 AS depth FROM categories WHERE id = 2
  UNION ALL
  SELECT c.id, c.name, w.depth + 1
  FROM categories c JOIN walk w ON c.parent_id = w.id
) CYCLE id SET is_cycle USING visited
SELECT id, name, depth, is_cycle FROM walk ORDER BY depth, id;

WITH RECURSIVE walk AS (
  SELECT id, name, ARRAY[id] AS visited FROM categories WHERE id = 2
  UNION ALL
  SELECT c.id, c.name, w.visited || c.id
  FROM categories c JOIN walk w ON c.parent_id = w.id
  WHERE NOT c.id = ANY (w.visited)
)
SELECT id, name, visited FROM walk ORDER BY cardinality(visited), id;
ROLLBACK;
Expected output
 id |  name   | depth | is_cycle 
----+---------+-------+----------
  2 | Kitchen |     0 | f
  3 | Knives  |     1 | f
  4 | Pans    |     1 | f
  1 | Home    |     2 | f
  2 | Kitchen |     3 | t
  5 | Garden  |     3 | f
  6 | Tools   |     4 | f
(7 rows)

 id |  name   |   visited   
----+---------+-------------
  2 | Kitchen | {2}
  3 | Knives  | {2,3}
  4 | Pans    | {2,4}
  1 | Home    | {2,3,1}
  5 | Garden  | {2,3,1,5}
  6 | Tools   | {2,3,1,5,6}
(6 rows)

In the first result, Kitchen appears a second time at depth 3 with is_cycle = t, and the walk does not continue from it. The second result simply leaves the repeat out. Either way the query finishes. A guard is cheap, so add one to any recursive query over data you do not fully control, and also fix the data: a check that every category reaches a root is a good data-quality test.

08. Check your understanding

Practice check · 3 questions

CTEs and recursion

These questions use new data. Pick the best answer.

Q1. The closure query from step 5 runs on a chain of three categories, A → B → C (A is the root, C the leaf). How many (ancestor, descendant) rows does `sub` return?
Q2. In PostgreSQL 17, `events` has an index on `(user_id, ts)`. You run `WITH recent AS (SELECT * FROM events WHERE ts > now() - interval '1 day') SELECT * FROM recent WHERE user_id = 7;`. What does the planner do?
Q3. Which statement describes how PostgreSQL evaluates the recursive term of a `WITH RECURSIVE` query?
Practice only: not graded, not saved, not evidence.

09. Apply it

The practice project asks for a category hierarchy built with a recursive CTE. Use the tree database or your own hierarchy:

  1. Walk up from Shoes to its root and return the breadcrumb "Sport > Running > Shoes" as one string. Decide which way the join goes before you write it.
  2. Add a depth limit as a second guard (WHERE w.depth < 10) and explain when it would hide a real problem.
  3. Rewrite your longest report query from the window functions lab as a CTE chain, and debug it by running each step on its own.

10. Review prompt

Without looking back, explain:

  • three reasons to split a query into CTEs, and how you debug one step;
  • when PostgreSQL 17 inlines a CTE and when it materialises one;
  • what the anchor, the recursive term and the working table are, and what ends the recursion;
  • how a closure of (ancestor, descendant) pairs lets you roll values up a tree;
  • two ways to keep a recursive query from looping forever on a cycle.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check