Courses / Databases for Backend Interviews / Chapter 14
Module 7 · SQL patterns: comparing, sequencing and reshaping · Chapter 14 of 27
Sequencing and Hierarchy Patterns: Streaks, Sessions and Recursive Trees
Builds on Comparison Patterns: Row Against Group, Neighbour and Earlier Period. Next up: Transformation Patterns: Pivoting, Unpivoting, Text and JSON.
Part 1 · Numbering events
Position in a sequence
Streaks, sessions and org charts are all questions about order or about parent and child.
A sequencing question depends on where a row sits among related rows: the first order a customer ever placed, their third order, the latest one. A hierarchical question depends on how rows point at each other: a category inside a category, a staff member under a manager. Plain GROUP BY cannot answer either, because grouping throws the order away.
The first tool is the window function: a function that looks at a set of related rows, called a window, without collapsing them into one row. row_number() is the simplest. For every row it returns 1, 2, 3 and so on, counting inside a partition (the rows that share a value, such as one customer) in the order given by the window's ORDER BY.
The chapter has its own small data, in the grocery delivery schema from the patterns introduction. It uses the tables for cities, stores, customers, orders, app events, categories and staff, and adds one table of its own, store_links, for delivery routes between stores. The orders do not need their lines here, so order_items and products are left out. Results are printed with the helper from the SQL chapter.
SET TIME ZONE 'Asia/Kolkata'; CREATE TABLE cities ( city_id int PRIMARY KEY, name text NOT NULL, state text NOT NULL ); CREATE TABLE stores ( store_id int PRIMARY KEY, city_id int NOT NULL REFERENCES cities (city_id), name text NOT NULL, opened_on date NOT NULL ); CREATE TABLE customers ( customer_id int PRIMARY KEY, name text NOT NULL, city_id int NOT NULL REFERENCES cities (city_id), signed_up_at timestamptz NOT NULL ); CREATE TABLE orders ( order_id int PRIMARY KEY, customer_id int NOT NULL REFERENCES customers (customer_id), store_id int NOT NULL REFERENCES stores (store_id), placed_at timestamptz NOT NULL, status text NOT NULL CHECK (status IN ('placed', 'delivered', 'cancelled')) );
CREATE TABLE app_events ( customer_id int NOT NULL REFERENCES customers (customer_id), event_at timestamptz NOT NULL, event_type text NOT NULL ); CREATE TABLE categories ( category_id int PRIMARY KEY, name text NOT NULL, parent_id int REFERENCES categories (category_id) ); CREATE TABLE staff ( staff_id int PRIMARY KEY, name text NOT NULL, store_id int NOT NULL REFERENCES stores (store_id), manager_id int REFERENCES staff (staff_id), role text NOT NULL, salary numeric(10,2) NOT NULL ); CREATE TABLE store_links ( from_store int NOT NULL REFERENCES stores (store_id), to_store int NOT NULL REFERENCES stores (store_id), PRIMARY KEY (from_store, to_store) );
The data
Everything happens in Pune in March 2026. Three customers placed thirteen orders. Asha ordered on four days in a row and then on two more. Ravi's orders 9 and 10 carry the very same timestamp, which is a tie that the next page has to handle. Meera's second order was cancelled. Ten app events belong to 9 March. The category tree is three levels deep below its root, the staff chart has four levels with a trainee at the bottom, and the store links contain a loop on purpose.
INSERT INTO cities (city_id, name, state) VALUES (1, 'Pune', 'Maharashtra'); INSERT INTO stores (store_id, city_id, name, opened_on) VALUES (1, 1, 'Kothrud', '2024-02-10'), (2, 1, 'Viman Nagar', '2024-08-01'), (3, 1, 'Baner', '2025-01-15'), (4, 1, 'Hadapsar', '2025-06-20'), (5, 1, 'Wakad', '2025-09-05'); INSERT INTO customers (customer_id, name, city_id, signed_up_at) VALUES (1, 'Asha', 1, '2025-11-03 10:00'), (2, 'Ravi', 1, '2025-12-14 18:30'), (3, 'Meera', 1, '2026-01-09 09:15'); INSERT INTO orders (order_id, customer_id, store_id, placed_at, status) VALUES (1, 1, 1, '2026-03-02 09:15', 'delivered'), (2, 1, 1, '2026-03-03 18:40', 'delivered'), (3, 1, 2, '2026-03-04 08:05', 'delivered'), (4, 1, 1, '2026-03-05 19:30', 'delivered'), (5, 1, 1, '2026-03-08 10:00', 'delivered'), (6, 1, 2, '2026-03-09 21:10', 'delivered'), (7, 2, 2, '2026-03-03 12:00', 'delivered'), (8, 2, 2, '2026-03-05 20:15', 'delivered'), (9, 2, 1, '2026-03-06 11:00', 'delivered'), (10, 2, 1, '2026-03-06 11:00', 'delivered'), (11, 2, 2, '2026-03-07 07:45', 'delivered'), (12, 3, 1, '2026-03-10 13:20', 'delivered'), (13, 3, 1, '2026-03-12 17:05', 'cancelled');
INSERT INTO app_events (customer_id, event_at, event_type) VALUES (1, '2026-03-09 09:00', 'open'), (1, '2026-03-09 09:10', 'search'), (1, '2026-03-09 09:25', 'add_to_cart'), (1, '2026-03-09 10:10', 'open'), (1, '2026-03-09 10:20', 'checkout'), (1, '2026-03-09 14:00', 'open'), (2, '2026-03-09 09:05', 'open'), (2, '2026-03-09 09:40', 'search'), (2, '2026-03-09 09:50', 'add_to_cart'), (2, '2026-03-09 10:20', 'checkout'); INSERT INTO categories (category_id, name, parent_id) VALUES (1, 'Groceries', NULL), (2, 'Dairy', 1), (3, 'Staples', 1), (4, 'Snacks', 1), (5, 'Milk', 2), (6, 'Curd', 2), (7, 'Rice', 3), (8, 'Flour', 3), (9, 'Basmati', 7); INSERT INTO staff (staff_id, name, store_id, manager_id, role, salary) VALUES (1, 'Meenal', 1, NULL, 'area manager', 90000.00), (2, 'Suresh', 1, 1, 'store manager', 55000.00), (3, 'Kavita', 2, 1, 'store manager', 52000.00), (4, 'Arjun', 1, 2, 'picker', 22000.00), (5, 'Pooja', 1, 2, 'picker', 23000.00), (6, 'Nitin', 2, 3, 'picker', 21000.00), (7, 'Farah', 2, 3, 'rider', 20000.00), (8, 'Dev', 1, 5, 'trainee', 15000.00); INSERT INTO store_links (from_store, to_store) VALUES (1, 2), (1, 3), (2, 4), (3, 4), (4, 5), (5, 2);
Numbering with ROW_NUMBER
Number each customer's orders from the oldest. The partition is the customer, and the order inside it is the time of the order.
SELECT order_id, customer_id, placed_at::date::text AS day, row_number() OVER ( PARTITION BY customer_id ORDER BY placed_at, order_id ) AS nth FROM orders ORDER BY customer_id, nth;
order_id | customer_id | day | nth ---------+-------------+------------+---- 1 | 1 | 2026-03-02 | 1 2 | 1 | 2026-03-03 | 2 3 | 1 | 2026-03-04 | 3 4 | 1 | 2026-03-05 | 4 5 | 1 | 2026-03-08 | 5 6 | 1 | 2026-03-09 | 6 7 | 2 | 2026-03-03 | 1 8 | 2 | 2026-03-05 | 2 9 | 2 | 2026-03-06 | 3 10 | 2 | 2026-03-06 | 4 11 | 2 | 2026-03-07 | 5 12 | 3 | 2026-03-10 | 1 13 | 3 | 2026-03-12 | 2 (13 rows)
Look at orders 9 and 10. They were placed at the same instant, so ORDER BY placed_at alone cannot say which comes first. PostgreSQL would still give one of them 3 and the other 4, and which one gets which is not defined. Adding order_id as a second sort key, a tiebreaker, makes the numbering the same every time. Any numbering by a column that can repeat needs one.
The number is computed after WHERE, GROUP BY and HAVING, so it exists only in the SELECT list and ORDER BY. You cannot write WHERE row_number() OVER (...) = 1. The usual fix is to compute the number in a subquery or a CTE and filter in the outer query, which is what the next page does.
First, last and nth
With the number available, "the first order of each customer" is a filter on 1.
SELECT customer_id, order_id, placed_at::text AS first_order_at FROM ( SELECT customer_id, order_id, placed_at, row_number() OVER ( PARTITION BY customer_id ORDER BY placed_at, order_id ) AS nth FROM orders ) AS numbered WHERE nth = 1 ORDER BY customer_id;
customer_id | order_id | first_order_at ------------+----------+-------------------------- 1 | 1 | 2026-03-02 09:15:00+05:30 2 | 7 | 2026-03-03 12:00:00+05:30 3 | 12 | 2026-03-10 13:20:00+05:30 (3 rows)
The last order is the same idea with the sort reversed, so that the newest row gets 1. Keep the tiebreaker reversed as well.
SELECT customer_id, order_id, placed_at::text AS last_order_at FROM ( SELECT customer_id, order_id, placed_at, row_number() OVER ( PARTITION BY customer_id ORDER BY placed_at DESC, order_id DESC ) AS nth_from_end FROM orders ) AS numbered WHERE nth_from_end = 1 ORDER BY customer_id;
customer_id | order_id | last_order_at ------------+----------+-------------------------- 1 | 6 | 2026-03-09 21:10:00+05:30 2 | 11 | 2026-03-07 07:45:00+05:30 3 | 13 | 2026-03-12 17:05:00+05:30 (3 rows)
The nth order is a filter on n. Here it is the second order of each customer, which is how you ask "who came back at all, and when".
SELECT customer_id, order_id, nth FROM ( SELECT customer_id, order_id, row_number() OVER ( PARTITION BY customer_id ORDER BY placed_at, order_id ) AS nth FROM orders ) AS numbered WHERE nth = 2 ORDER BY customer_id;
customer_id | order_id | nth ------------+----------+---- 1 | 2 | 2 2 | 8 | 2 3 | 13 | 2 (3 rows)
Meera's second order is the cancelled one. A real report would filter on status before numbering, inside the subquery, so that a cancelled order does not count as a return. Whether it should count is a business rule to ask about.
There is also a way to find the last row without sorting twice: count the rows in the partition and compare. count(*) OVER (PARTITION BY customer_id) puts the partition size on every row, and the last row is the one whose number equals it. Two window functions with the same partition and ordering can share a named window with the WINDOW clause, which keeps the query readable.
Part 2 · Gaps and islands
Streaks are islands
Retention teams ask how many days in a row a customer ordered. A run of consecutive days is an island, and the days missing between runs are the gaps. "Gaps and islands" is the standard name for finding either, and it comes up whenever the data has a natural step: consecutive days, consecutive invoice numbers, consecutive seats.
The difficulty is that SQL has no idea that 4 March follows 3 March. Rows are only a set. To see a streak you need a value that stays the same for every row inside one run and changes when the run breaks. Then you can group by that value.
There is such a value, and it needs only a window function. Number the days of each customer 1, 2, 3 in date order. Inside a streak, the day moves forward by one and the row number moves forward by one, so the day minus the row number is constant. When a day is skipped, the day jumps while the row number still moves by one, so the difference becomes larger. The difference is only a label for the island, and its meaning does not matter.
Dates and integers combine in PostgreSQL: date - integer gives a date, the earlier day. That is why the label below is itself a date.
The difference as a label
Step one is to reduce the orders to one row per customer per day. A customer can order twice in a day, and Ravi did, so duplicates must go first. Cancelled orders are left out, because a cancelled order is not a purchase day.
SELECT DISTINCT customer_id, placed_at::date::text AS day FROM orders WHERE status <> 'cancelled' ORDER BY customer_id, day;
customer_id | day ------------+----------- 1 | 2026-03-02 1 | 2026-03-03 1 | 2026-03-04 1 | 2026-03-05 1 | 2026-03-08 1 | 2026-03-09 2 | 2026-03-03 2 | 2026-03-05 2 | 2026-03-06 2 | 2026-03-07 3 | 2026-03-10 (11 rows)
Step two numbers the days and subtracts the number from the day.
SELECT customer_id, day::text AS day, row_number() OVER (PARTITION BY customer_id ORDER BY day) AS rn, (day - row_number() OVER ( PARTITION BY customer_id ORDER BY day)::int)::text AS grp FROM (SELECT DISTINCT customer_id, placed_at::date AS day FROM orders WHERE status <> 'cancelled') AS d ORDER BY customer_id, day;
customer_id | day | rn | grp ------------+------------+----+----------- 1 | 2026-03-02 | 1 | 2026-03-01 1 | 2026-03-03 | 2 | 2026-03-01 1 | 2026-03-04 | 3 | 2026-03-01 1 | 2026-03-05 | 4 | 2026-03-01 1 | 2026-03-08 | 5 | 2026-03-03 1 | 2026-03-09 | 6 | 2026-03-03 2 | 2026-03-03 | 1 | 2026-03-02 2 | 2026-03-05 | 2 | 2026-03-03 2 | 2026-03-06 | 3 | 2026-03-03 2 | 2026-03-07 | 4 | 2026-03-03 3 | 2026-03-10 | 1 | 2026-03-09 (11 rows)
Asha's first four days all show 2026-03-01, and her last two show 2026-03-03. Ravi has two islands too. Meera has one.
Watch for grp: it stays the same while the days follow each other without a gap
Read it as steps
Grouping the islands
Now group by customer and label. Each group is one island, so the smallest and largest day give its edges and the row count gives its length.
WITH days AS ( SELECT DISTINCT customer_id, placed_at::date AS day FROM orders WHERE status <> 'cancelled' ), grouped AS ( SELECT customer_id, day, day - (row_number() OVER ( PARTITION BY customer_id ORDER BY day ))::int AS grp FROM days ) SELECT customer_id, min(day)::text AS first_day, max(day)::text AS last_day, count(*) AS streak_days FROM grouped GROUP BY customer_id, grp ORDER BY customer_id, first_day;
customer_id | first_day | last_day | streak_days ------------+------------+------------+------------ 1 | 2026-03-02 | 2026-03-05 | 4 1 | 2026-03-08 | 2026-03-09 | 2 2 | 2026-03-03 | 2026-03-03 | 1 2 | 2026-03-05 | 2026-03-07 | 3 3 | 2026-03-10 | 2026-03-10 | 1 (5 rows)
To keep only each customer's longest streak, number the islands by length in a third step and keep number 1. A second sort key picks the earlier island when two islands are equally long, otherwise the choice between them would be undefined.
WITH days AS ( SELECT DISTINCT customer_id, placed_at::date AS day FROM orders WHERE status <> 'cancelled' ), grouped AS ( SELECT customer_id, day, day - (row_number() OVER ( PARTITION BY customer_id ORDER BY day ))::int AS grp FROM days ), islands AS ( SELECT customer_id, min(day) AS first_day, max(day) AS last_day, count(*) AS streak_days FROM grouped GROUP BY customer_id, grp ), ranked AS ( SELECT customer_id, first_day, last_day, streak_days, row_number() OVER ( PARTITION BY customer_id ORDER BY streak_days DESC, first_day ) AS rk FROM islands ) SELECT customer_id, first_day::text AS first_day, last_day::text AS last_day, streak_days FROM ranked WHERE rk = 1 ORDER BY customer_id;
customer_id | first_day | last_day | streak_days ------------+------------+------------+------------ 1 | 2026-03-02 | 2026-03-05 | 4 2 | 2026-03-05 | 2026-03-07 | 3 3 | 2026-03-10 | 2026-03-10 | 1 (3 rows)
Asha's longest streak is four days from 2 to 5 March, and Ravi's is three days from 5 to 7 March, even though he ordered five times in total.
What goes wrong without DISTINCT
The deduplication in step one is not optional. Without it, Ravi's two orders on 6 March give two rows for the same day, the row numbers advance by two for that single day, and the subtraction no longer separates islands correctly. Here is the same grouping with the duplicates left in, for Ravi only.
SELECT customer_id, min(day)::text AS first_day, max(day)::text AS last_day, count(*) AS counted_days FROM ( SELECT customer_id, day, day - (row_number() OVER ( PARTITION BY customer_id ORDER BY day))::int AS grp FROM (SELECT customer_id, placed_at::date AS day FROM orders WHERE status <> 'cancelled' AND customer_id = 2) AS d ) AS g GROUP BY customer_id, grp ORDER BY first_day;
customer_id | first_day | last_day | counted_days ------------+------------+------------+------------- 2 | 2026-03-03 | 2026-03-07 | 3 2 | 2026-03-05 | 2026-03-06 | 2 (2 rows)
The result claims that Ravi has an island from 3 to 7 March with three rows and another from 5 to 6 March. Both are wrong, and the query raised no error. Two fixes exist. One is the DISTINCT you already used. The other is dense_rank() in place of row_number(), which gives equal days the same number, so the two rows of 6 March share a label. A count over such an island would then need count(DISTINCT day).
SELECT customer_id, day::text AS day, (day - (dense_rank() OVER ( PARTITION BY customer_id ORDER BY day))::int)::text AS grp FROM (SELECT customer_id, placed_at::date AS day FROM orders WHERE status <> 'cancelled' AND customer_id = 2) AS d ORDER BY day;
customer_id | day | grp ------------+------------+----------- 2 | 2026-03-03 | 2026-03-02 2 | 2026-03-05 | 2026-03-03 2 | 2026-03-06 | 2026-03-03 2 | 2026-03-06 | 2026-03-03 2 | 2026-03-07 | 2026-03-03 (5 rows)
The same method works for any step, not only one day. For weeks, truncate the date to the week first and subtract the row number times seven days. For numbered records, such as invoice numbers, subtract the row number directly from the number. A related problem, finding the gaps themselves, uses lag() to compare each row with the previous one and keeps the rows where the difference is more than one step.
Inside one streak, what stays constant, and why?
Part 3 · Sessions
A session is a burst of activity
A session is a burst of activity by one user, closed by a pause long enough to say they left. The app_events table does not store sessions. It stores single events, and product analytics wants sessions: how many per day, how long, and how many reached the checkout.
The rule used here is common but arbitrary, and it is the first thing to agree on: a new session starts when more than 30 minutes have passed since the same customer's previous event. A pause of exactly 30 minutes keeps the session going. Change the number and the rule changes; the query does not.
Unlike the streak, a session has no arithmetic label. The label has to be built in three small steps: measure the gap to the previous event, mark the events that start a session, and add up the marks. Each step is a window function, and each reads the output of the step before it, so they sit in CTEs.
A simpler idea is to group events by customer and day, and call each group a session. It fails in both directions. A customer who browses in the morning and orders in the evening has two sessions on one day, and a customer who is still active at midnight has one session that crosses two days. A session is defined by the pauses between events, not by the calendar.
The events are ten rows on 9 March, for customers 1 and 2. Customer 1 has pauses of 45 minutes and 3 hours 40 minutes. Customer 2 has a pause of 35 minutes, and later a gap of exactly 30 minutes that must not split a session.
SELECT customer_id, event_at::time::text AS at, event_type, (event_at - lag(event_at) OVER ( PARTITION BY customer_id ORDER BY event_at))::text AS gap FROM app_events ORDER BY customer_id, event_at;
customer_id | at | event_type | gap ------------+----------+-------------+--------- 1 | 09:00:00 | open | NULL 1 | 09:10:00 | search | 00:10:00 1 | 09:25:00 | add_to_cart | 00:15:00 1 | 10:10:00 | open | 00:45:00 1 | 10:20:00 | checkout | 00:10:00 1 | 14:00:00 | open | 03:40:00 2 | 09:05:00 | open | NULL 2 | 09:40:00 | search | 00:35:00 2 | 09:50:00 | add_to_cart | 00:10:00 2 | 10:20:00 | checkout | 00:30:00 (10 rows)
Flag, then count the flags
The gap is the event time minus lag() of the event time, which is NULL on the first event of each customer. A first event always starts a session, so the flag is 1 when the previous event is missing or the gap is more than 30 minutes, and 0 otherwise. Written with a named window, the flag query is short.
SELECT customer_id, event_at::time::text AS at, CASE WHEN lag(event_at) OVER w IS NULL OR event_at - lag(event_at) OVER w > interval '30 minutes' THEN 1 ELSE 0 END AS new_session FROM app_events WINDOW w AS (PARTITION BY customer_id ORDER BY event_at) ORDER BY customer_id, event_at;
customer_id | at | new_session ------------+----------+------------ 1 | 09:00:00 | 1 1 | 09:10:00 | 0 1 | 09:25:00 | 0 1 | 10:10:00 | 1 1 | 10:20:00 | 0 1 | 14:00:00 | 1 2 | 09:05:00 | 1 2 | 09:40:00 | 1 2 | 09:50:00 | 0 2 | 10:20:00 | 0 (10 rows)
The flag marks the start. The session number is the running total of the flags. A running sum over the events in time order adds 1 at each start, so every event gets the number of the session it belongs to, counted from the customer's first event.
WITH flagged AS ( SELECT customer_id, event_at, event_type, CASE WHEN lag(event_at) OVER w IS NULL OR event_at - lag(event_at) OVER w > interval '30 minutes' THEN 1 ELSE 0 END AS new_session FROM app_events WINDOW w AS (PARTITION BY customer_id ORDER BY event_at) ) SELECT customer_id, event_at::time::text AS at, new_session, sum(new_session) OVER ( PARTITION BY customer_id ORDER BY event_at ) AS session_no FROM flagged ORDER BY customer_id, event_at;
customer_id | at | new_session | session_no ------------+----------+-------------+----------- 1 | 09:00:00 | 1 | 1 1 | 09:10:00 | 0 | 1 1 | 09:25:00 | 0 | 1 1 | 10:10:00 | 1 | 2 1 | 10:20:00 | 0 | 2 1 | 14:00:00 | 1 | 3 2 | 09:05:00 | 1 | 1 2 | 09:40:00 | 1 | 2 2 | 09:50:00 | 0 | 2 2 | 10:20:00 | 0 | 2 (10 rows)
Read customer 2. The event at 09:40 is a start because the gap is 35 minutes. The event at 10:20 is 30 minutes after 09:50, which is not more than 30, so it stays in session 2. Using > instead of >= is the entire difference, so say which one the rule means.
One row per session
With a session number on every event, the rest is ordinary grouping. Group by customer and session number to get when each session started and ended, how many events it held, how long it lasted, and whether any event in it was a checkout. bool_or returns true if at least one value is true.
WITH flagged AS ( SELECT customer_id, event_at, event_type, CASE WHEN lag(event_at) OVER w IS NULL OR event_at - lag(event_at) OVER w > interval '30 minutes' THEN 1 ELSE 0 END AS new_session FROM app_events WINDOW w AS (PARTITION BY customer_id ORDER BY event_at) ), numbered AS ( SELECT customer_id, event_at, event_type, sum(new_session) OVER ( PARTITION BY customer_id ORDER BY event_at ) AS session_no FROM flagged ) SELECT customer_id AS customer, session_no AS session, min(event_at)::time::text AS started, max(event_at)::time::text AS ended, count(*) AS events, (max(event_at) - min(event_at))::text AS length, bool_or(event_type = 'checkout') AS checkout FROM numbered GROUP BY customer_id, session_no ORDER BY customer_id, session_no;
customer | session | started | ended | events | length | checkout ---------+---------+----------+----------+--------+----------+--------- 1 | 1 | 09:00:00 | 09:25:00 | 3 | 00:25:00 | false 1 | 2 | 10:10:00 | 10:20:00 | 2 | 00:10:00 | true 1 | 3 | 14:00:00 | 14:00:00 | 1 | 00:00:00 | false 2 | 1 | 09:05:00 | 09:05:00 | 1 | 00:00:00 | false 2 | 2 | 09:40:00 | 10:20:00 | 3 | 00:40:00 | true (5 rows)
Five sessions in all. Customer 1 has three, and only the second reached the checkout. Customer 2 has two. A session with one event has length zero, which is how a single visit looks when only events are recorded.
The total number of sessions per customer does not need the grouping step. It is the sum of the flags, because each flag is one session start.
WITH flagged AS ( SELECT customer_id, event_at, CASE WHEN lag(event_at) OVER w IS NULL OR event_at - lag(event_at) OVER w > interval '30 minutes' THEN 1 ELSE 0 END AS new_session FROM app_events WINDOW w AS (PARTITION BY customer_id ORDER BY event_at) ) SELECT customer_id, sum(new_session) AS sessions FROM flagged GROUP BY customer_id ORDER BY customer_id;
customer_id | sessions ------------+--------- 1 | 3 2 | 2 (2 rows)
Part 4 · How a recursive CTE runs
When the depth is not known
A category tree is as deep as someone made it. A query that joins categories to itself once finds the parent, twice finds the grandparent, and you must stop at some fixed depth. A recursive CTE keeps joining until there is nothing new, so one query handles any depth.
A recursive common table expression has two parts joined by UNION ALL (or UNION). The non-recursive term runs once and gives the starting rows. The recursive term refers to the CTE's own name and runs again and again. The simplest possible example counts from 1 to 5.
Read it as a loop. Start with the rows of the first term. Run the second term on the rows found last time. Keep what it returns, and repeat until it returns nothing. The counter has one row per round, which is the easiest case to follow, and the sections below show what happens when a round returns many rows.
WITH RECURSIVE counter (n) AS ( SELECT 1 UNION ALL SELECT n + 1 FROM counter WHERE n < 5 ) SELECT n FROM counter;
n - 1 2 3 4 5 (5 rows)
The same shape generates dates. Start from one date and add a day each round, with the stop condition in WHERE. In practice generate_series is simpler for dates, but the recursive form is the one that also handles trees, so it is worth seeing here.
WITH RECURSIVE days (day) AS ( SELECT date '2026-03-01' UNION ALL SELECT (day + 1) FROM days WHERE day < date '2026-03-05' ) SELECT day::text AS day, to_char(day, 'Dy') AS weekday FROM days;
day | weekday -----------+-------- 2026-03-01 | Sun 2026-03-02 | Mon 2026-03-03 | Tue 2026-03-04 | Wed 2026-03-05 | Thu (5 rows)
The working table
According to the PostgreSQL documentation, evaluation is iterative, in these steps. First the non-recursive term runs, and its rows go to the result and into a temporary working table. Then, while the working table is not empty, the recursive term runs with the working table in place of its own name. Its output rows are added to the result and are collected in an intermediate table. At the end of each round the intermediate table replaces the working table and is emptied. When a round produces no rows, the query stops.
Two facts follow. The recursive term only ever sees the rows from the last round, not everything found so far. And the query stops by itself only when some round finds no rows, so the recursive term needs a way to run out. In the counter, the WHERE n < 5 does that: after n = 5 the round returns nothing.
A doubling series makes the rounds visible. The round column is carried along as an ordinary column, and each round holds exactly one row.
WITH RECURSIVE fan (round, n) AS ( SELECT 0, 1 UNION ALL SELECT round + 1, n * 2 FROM fan WHERE round < 4 ) SELECT round, n FROM fan;
round | n ------+--- 0 | 1 1 | 2 2 | 4 3 | 8 4 | 16 (5 rows)
The query plan agrees with the description. It shows a Recursive Union node with the starting Result and a WorkTable Scan that carries the stop condition as its filter.
EXPLAIN (COSTS OFF) WITH RECURSIVE counter (n) AS ( SELECT 1 UNION ALL SELECT n + 1 FROM counter WHERE n < 5 ) SELECT n FROM counter;
QUERY PLAN
-------------------------------------------------
CTE Scan on counter
CTE counter
-> Recursive Union
-> Result
-> WorkTable Scan on counter counter_1
Filter: (n < 5)
(6 rows)UNION, UNION ALL and stopping
With UNION ALL every row is kept. With UNION, duplicates are discarded, both inside a round and against all earlier rows. That makes UNION a safety net for some loops: a row that has been seen before is not produced again, so the working table eventually becomes empty. The ring below would cycle 1, 2, 3, 1, 2, 3 for ever with UNION ALL, yet with UNION it ends after three rows.
WITH RECURSIVE ring (n) AS ( SELECT 1 UNION SELECT (n % 3) + 1 FROM ring ) SELECT n FROM ring ORDER BY n;
n - 1 2 3 (3 rows)
The net is narrow. It only works when the repeated rows are identical in every column. If a row also carries a depth or a path that changes every round, no two rows are equal and the loop is not stopped. The next lessons use a path column and handle cycles explicitly.
Endless recursion and output order
LIMIT in the outer query can also stop an endless recursion, because PostgreSQL produces only as many rows as the outer query asks for. The documentation offers it as a trick for testing a query that might loop, and says that using it in production is not recommended, because other systems might work differently. The run below stops after three rows only because LIMIT is there.
WITH RECURSIVE forever (n) AS ( SELECT 1 UNION ALL SELECT n + 1 FROM forever ) SELECT n FROM forever LIMIT 3;
n - 1 2 3 (3 rows)
The trick stops working when the outer query needs every row before it can answer, for example when it sorts. The next query asks for the three largest values of the same endless series. The run was made on a real PostgreSQL 18.6 server with a statement timeout of two seconds, because PGlite has no timer to cancel a statement, and the exact wait varies.
SET statement_timeout = '2s'; WITH RECURSIVE forever (n) AS ( SELECT 1 UNION ALL SELECT n + 1 FROM forever ) SELECT n FROM forever ORDER BY n DESC LIMIT 3;
ERROR 57014: canceling statement due to statement timeoutSQLSTATE 57014 is query_canceled. Without the timeout nothing would end the statement, so always have a stop condition in the recursive term and treat LIMIT as a testing aid only.
Last, the order of the output. The documentation says that the algorithm produces its output in breadth-first order, but that this is an implementation detail and perhaps unsound to rely on, and that the order of the rows within each level is certainly undefined. When the order matters, sort by a column that carries it, such as the depth, the path, or the SEARCH ordering column that the last lesson of this chapter introduces.
What does the recursive term see in each round?
- Only the rows produced by the previous round, held in the working table.
- It does not see the whole result accumulated so far.
Why does a recursive CTE need a stop condition or a way to run out of rows?
Part 5 · Trees
Walking down the category tree
The categories table stores a tree with one link per row: each category points at its parent, and the roots have a NULL parent. This is called an adjacency list. It is simple to write and update, and the cost is that reading a whole subtree needs a recursive query.
The starting rows are the roots. The recursive term joins categories to the working table on parent_id, so every round finds the children of the rows found in the last round. Two columns are carried along. Depth counts the levels from the root. Path is the text of the names from the root, built by appending the child's name to its parent's path.
WITH RECURSIVE tree (category_id, name, depth, path) AS ( SELECT category_id, name, 0, name FROM categories WHERE parent_id IS NULL UNION ALL SELECT c.category_id, c.name, t.depth + 1, t.path || ' > ' || c.name FROM categories AS c JOIN tree AS t ON c.parent_id = t.category_id ) SELECT category_id, depth, path FROM tree ORDER BY path;
category_id | depth | path ------------+-------+------------------------------------- 1 | 0 | Groceries 2 | 1 | Groceries > Dairy 6 | 2 | Groceries > Dairy > Curd 5 | 2 | Groceries > Dairy > Milk 4 | 1 | Groceries > Snacks 3 | 1 | Groceries > Staples 8 | 2 | Groceries > Staples > Flour 7 | 2 | Groceries > Staples > Rice 9 | 3 | Groceries > Staples > Rice > Basmati (9 rows)
Sorting by the path puts every category directly under its parent, which gives an indented outline without any other work. Rice has depth 2 and its child Basmati has depth 3, and Snacks is a leaf at depth 1.
One subtree, or the way up
To get the subtree of one category, start from that one row instead of from the roots. The recursion then finds everything beneath it. Staples contains Rice, Flour and Basmati.
WITH RECURSIVE sub (category_id, name) AS ( SELECT category_id, name FROM categories WHERE name = 'Staples' UNION ALL SELECT c.category_id, c.name FROM categories AS c JOIN sub AS s ON c.parent_id = s.category_id ) SELECT category_id, name FROM sub ORDER BY category_id;
category_id | name ------------+-------- 3 | Staples 7 | Rice 8 | Flour 9 | Basmati (4 rows)
The direction can be reversed. To find all ancestors of a category, start from it and join on the other side: the next row is the category whose id equals the current row's parent. This is the way to build a breadcrumb for a product page, and the chain ends by itself at the root, whose parent is NULL and matches nothing.
WITH RECURSIVE up (category_id, name, parent_id) AS ( SELECT category_id, name, parent_id FROM categories WHERE name = 'Basmati' UNION ALL SELECT c.category_id, c.name, c.parent_id FROM categories AS c JOIN up AS u ON c.category_id = u.parent_id ) SELECT category_id, name FROM up;
category_id | name ------------+---------- 9 | Basmati 7 | Rice 3 | Staples 1 | Groceries (4 rows)
Both queries use the same two-part shape. Only the starting row and the direction of the join change. Whenever a question says "everything under" or "everything above", start by deciding the starting rows and the join direction.
The staff chart
The staff table is a second tree, and its link is manager_id. Meenal, the area manager, has no manager and is the root. Everyone below her is a direct or an indirect report. The query for all reports of Meenal carries the depth, so you can see how far down each person sits.
WITH RECURSIVE chain (staff_id, name, manager_id, depth) AS ( SELECT staff_id, name, manager_id, 0 FROM staff WHERE name = 'Meenal' UNION ALL SELECT s.staff_id, s.name, s.manager_id, c.depth + 1 FROM staff AS s JOIN chain AS c ON s.manager_id = c.staff_id ) SELECT staff_id, name, depth FROM chain ORDER BY depth, staff_id;
staff_id | name | depth ---------+--------+------ 1 | Meenal | 0 2 | Suresh | 1 3 | Kavita | 1 4 | Arjun | 2 5 | Pooja | 2 6 | Nitin | 2 7 | Farah | 2 8 | Dev | 3 (8 rows)
Dev is three levels below Meenal, under Pooja, who is under Suresh. A fixed number of self-joins would have needed to know that in advance.
Watch for the working table: each round holds only the people found in the round before
Read it as steps
Totals for every manager
A common report asks for the size of each manager's team, including indirect reports, and the payroll under them. The trick is to start the recursion from every person at once, keeping the starting person as root_id. The recursive term carries root_id unchanged, so each row says "this person is somewhere below that root". A final GROUP BY root_id then counts and sums. Each person is also under themselves, so the count is reduced by one.
WITH RECURSIVE chain (root_id, staff_id) AS ( SELECT staff_id, staff_id FROM staff UNION ALL SELECT c.root_id, s.staff_id FROM staff AS s JOIN chain AS c ON s.manager_id = c.staff_id ) SELECT m.name, count(*) - 1 AS people_below, sum(s.salary) AS payroll FROM chain AS c JOIN staff AS m ON m.staff_id = c.root_id JOIN staff AS s ON s.staff_id = c.staff_id GROUP BY m.staff_id, m.name ORDER BY people_below DESC, m.name;
name | people_below | payroll -------+--------------+---------- Meenal | 7 | 298000.00 Suresh | 3 | 115000.00 Kavita | 2 | 93000.00 Pooja | 1 | 38000.00 Arjun | 0 | 22000.00 Dev | 0 | 15000.00 Farah | 0 | 20000.00 Nitin | 0 | 21000.00 (8 rows)
Meenal has seven people below her and a payroll of 2,98,000 rupees for the whole team including herself. People with nobody below them show 0, and the second sort key, the name, fixes their order.
An indented chart is a matter of presentation. Repeating two spaces for each level of depth and sorting by the full path gives a text org chart.
WITH RECURSIVE chart (staff_id, name, depth, line) AS ( SELECT staff_id, name, 0, name FROM staff WHERE manager_id IS NULL UNION ALL SELECT s.staff_id, s.name, c.depth + 1, c.line || ' / ' || s.name FROM staff AS s JOIN chart AS c ON s.manager_id = c.staff_id ) SELECT repeat(' ', depth) || name AS chart, line FROM chart ORDER BY line;
chart | line
----------+------------------------------
Meenal | Meenal
Kavita | Meenal / Kavita
Farah | Meenal / Kavita / Farah
Nitin | Meenal / Kavita / Nitin
Suresh | Meenal / Suresh
Arjun | Meenal / Suresh / Arjun
Pooja | Meenal / Suresh / Pooja
Dev | Meenal / Suresh / Pooja / Dev
(8 rows)The two outputs hold the same people in two shapes. The chart lists everyone by their position, and the team report lists every manager with their total. If your tree is large and read far more often than it is changed, other designs trade write complexity for faster reads, such as storing the path in a column. For trees of a few thousand rows, the recursive CTE is the sensible default.
Part 6 · Graphs and cycles
From trees to graphs
A tree gives every row one parent. A graph allows any number of links between rows, so a row can be reached in more than one way, and the links can form a loop. The store_links table records which store can send stock to which, one direction per row.
SELECT from_store, to_store FROM store_links ORDER BY from_store, to_store;
from_store | to_store -----------+--------- 1 | 2 1 | 3 2 | 4 3 | 4 4 | 5 5 | 2 (6 rows)
Store 1 sends to 2 and 3. Both of those send on to 4, and store 4 sends to 5. Store 5 sends back to store 2. So 2, 4 and 5 form a loop. A recursive query that follows the links without caution would circle in it for ever.
A common way to stop that is to carry the route taken so far in an array and refuse to step to a store that is already on it. <> ALL(route) is true when the new store is not in the array, and route || l.to_store appends it.
WITH RECURSIVE reach (store_id, hops, route) AS ( SELECT 1, 0, ARRAY[1] UNION ALL SELECT l.to_store, r.hops + 1, r.route || l.to_store FROM store_links AS l JOIN reach AS r ON l.from_store = r.store_id WHERE l.to_store <> ALL (r.route) ) SELECT store_id, hops, route::text AS route FROM reach ORDER BY hops, store_id, route;
store_id | hops | route ---------+------+------------ 1 | 0 | {1} 2 | 1 | {1,2} 3 | 1 | {1,3} 4 | 2 | {1,2,4} 4 | 2 | {1,3,4} 5 | 3 | {1,2,4,5} 5 | 3 | {1,3,4,5} 2 | 4 | {1,3,4,5,2} (8 rows)
Paths and what they cost
Look at the result. The query now ends, because no route can contain a store twice. But the output is a list of routes, not of stores. Store 4 shows up twice, once through 2 and once through 3, and store 5 twice for the same reason. Store 2 even appears again at four hops, by going round the loop 1, 3, 4, 5 and back to 2.
That is the price of carrying the route: the query enumerates every path, and the number of paths can grow much faster than the number of stores. On a large graph with many ways between two points that can be very slow. If you only need which stores can be reached, use UNION and no path column, so that a store reached a second time is dropped.
WITH RECURSIVE reach (store_id) AS ( SELECT 1 UNION SELECT l.to_store FROM store_links AS l JOIN reach AS r ON l.from_store = r.store_id ) SELECT store_id FROM reach ORDER BY store_id;
store_id -------- 1 2 3 4 5 (5 rows)
That works because every row has the same single column, so a repeated store is a duplicate row and the working table runs dry. It tells you which stores are reachable and nothing more. It does not give the distance or the route. When you need those, you keep the extra columns and take care of the cycle yourself, which is what the next page makes easier.
Walking a graph this way is also the basis of questions such as which stores can eventually supply a given store, or which accounts are linked to one another through shared devices.
CYCLE and SEARCH
PostgreSQL has built-in syntax for both jobs. The CYCLE clause names the columns that identify a row, a column to hold the flag, and a column to hold the path. After each round it checks whether the new row's identifying columns already appear on its path. If they do, the row is returned with the flag set to true and is not expanded further. The path column is an array holding the identifying values of each step. In this run its type is an array of one-column rows (record[]), which is why every store is printed inside brackets. The documentation's own hand-written version, which the clause stands in for, uses a plain array when one column is enough, so do not rely on the exact shape of the built-in column.
WITH RECURSIVE reach (store_id, hops) AS ( SELECT 1, 0 UNION ALL SELECT l.to_store, r.hops + 1 FROM store_links AS l JOIN reach AS r ON l.from_store = r.store_id ) CYCLE store_id SET is_cycle USING route SELECT store_id, hops, is_cycle, route::text AS route FROM reach ORDER BY hops, store_id, route::text;
store_id | hops | is_cycle | route ---------+------+----------+-------------------------- 1 | 0 | false | {(1)} 2 | 1 | false | {(1),(2)} 3 | 1 | false | {(1),(3)} 4 | 2 | false | {(1),(2),(4)} 4 | 2 | false | {(1),(3),(4)} 5 | 3 | false | {(1),(2),(4),(5)} 5 | 3 | false | {(1),(3),(4),(5)} 2 | 4 | true | {(1),(2),(4),(5),(2)} 2 | 4 | false | {(1),(3),(4),(5),(2)} 4 | 5 | true | {(1),(3),(4),(5),(2),(4)} (10 rows)
The two rows for store 2 at four hops are different routes, one of which has already seen store 2 and is flagged as a cycle. The flagged row is still in the output, so a report that wants real routes filters on NOT is_cycle. That also gives the fewest hops to each store, taking the minimum.
WITH RECURSIVE reach (store_id, hops) AS ( SELECT 1, 0 UNION ALL SELECT l.to_store, r.hops + 1 FROM store_links AS l JOIN reach AS r ON l.from_store = r.store_id ) CYCLE store_id SET is_cycle USING route SELECT store_id, min(hops) AS fewest_hops FROM reach WHERE NOT is_cycle GROUP BY store_id ORDER BY store_id;
store_id | fewest_hops ---------+------------ 1 | 0 2 | 1 3 | 1 4 | 2 5 | 3 (5 rows)
SEARCH BREADTH FIRST BY store_id SET order_no adds a column that sorts the rows level by level, and SEARCH DEPTH FIRST sorts them by following one route to its end before backing up. The documentation says this only defines an order to sort by afterwards; it does not change in what order the rows are computed. So the ordering column has to appear in an ORDER BY. The query below prints the ordering column as text under another name, so that the sort still uses the real column. Sorting by a text copy would put (10,2) before (2,4).
A cycle in the data
Cycles are not only a property of graphs. A bad row in a tree table can create one too, and then an ordinary tree walk never ends. Here one row is damaged on purpose: Staples is given Basmati as its parent, although Basmati sits below Rice, which sits below Staples. The walk of the Staples subtree from the trees lesson now goes round the loop 3, 7, 9, 3 for ever.
UPDATE categories SET parent_id = 9 WHERE category_id = 3;
With plain UNION ALL and no stop condition the query does not end. On a real PostgreSQL 18.6 server with SET statement_timeout = '2s' the same walk was cancelled with error 57014, as in the earlier lesson. With a CYCLE clause it ends, and the row that closes the loop is flagged.
WITH RECURSIVE sub (category_id, name) AS ( SELECT category_id, name FROM categories WHERE name = 'Staples' UNION ALL SELECT c.category_id, c.name FROM categories AS c JOIN sub AS s ON c.parent_id = s.category_id ) CYCLE category_id SET is_cycle USING path SELECT category_id, name, is_cycle FROM sub ORDER BY category_id, is_cycle;
category_id | name | is_cycle ------------+---------+--------- 3 | Staples | false 3 | Staples | true 7 | Rice | false 8 | Flour | false 9 | Basmati | false (5 rows)
Category 3 appears twice. The second copy, reached through Basmati, is flagged and not expanded further. A report would filter on NOT is_cycle, and the data fix is to repair the bad row. A depth limit in the recursive term also stops the loop, but it returns the repeated rows, as the next run shows with a limit of four levels.
WITH RECURSIVE sub (category_id, depth) AS ( SELECT category_id, 0 FROM categories WHERE name = 'Staples' UNION ALL SELECT c.category_id, s.depth + 1 FROM categories AS c JOIN sub AS s ON c.parent_id = s.category_id WHERE s.depth < 4 ) SELECT category_id, depth FROM sub ORDER BY depth, category_id;
category_id | depth ------------+------ 3 | 0 7 | 1 8 | 1 9 | 2 3 | 3 7 | 4 8 | 4 (7 rows)
Staples, Rice and Flour come back a second time at depths 3 and 4. A depth limit protects the server and does not tell you that the data is wrong, which is why CYCLE is the better guard. The last check shows the types of the two columns that the clauses add.
All chapters · Previous: Comparison Patterns: Row Against Group, Neighbour and Earlier Period