← All lessons
Advanced SQL · Lesson 6 of 11

Self joins and recursive queries

Each row of staff has a manager_id pointing at another row of staff. To show each person with their manager's name, join the table to itself with two aliases, as if there were two copies. It's a LEFT JOIN so Rosa, who has no manager, stays:

SELECT e.name, e.role, m.name AS manager
FROM staff e
LEFT JOIN staff m ON m.id = e.manager_id
ORDER BY e.id;
Returns
name | role           | manager
-----+----------------+--------
Rosa | Owner          | NULL
Omar | Shop manager   | Rosa
Lena | Warehouse lead | Rosa
Kai  | Sales          | Omar
Mia  | Sales          | Omar
Theo | Packer         | Lena
Zara | Packer         | Lena
Ivy  | Support        | Omar
(8 rows)

A self join goes one level. To follow the chain all the way down, from Rosa to the people who report to the people who report to her, you need a recursive CTE. It has two parts joined by UNION ALL: a starting row, and a step that joins the CTE to the table to find the next level. The database repeats the step until it finds no new rows.

WITH RECURSIVE team AS (
  SELECT id, name, 0 AS depth FROM staff WHERE id = 2
  UNION ALL
  SELECT s.id, s.name, t.depth + 1
  FROM staff s
  JOIN team t ON s.manager_id = t.id
)
SELECT name, depth FROM team ORDER BY depth, name;
Returns
name | depth
-----+------
Omar | 0
Ivy  | 1
Kai  | 1
Mia  | 1
(4 rows)

That's Omar's part of the shop: Omar at depth 0, then the three who report to him. Start at Rosa and you'd get everyone. The step must eventually find nothing, or the query runs forever; with real data that can mean a loop (A manages B, B manages A), so production queries often add a depth limit like WHERE t.depth < 20.

Recursion can also make rows from nothing, which is useful for a calendar to join against:

WITH RECURSIVE days AS (
  SELECT '2024-10-01' AS day
  UNION ALL
  SELECT date(day, '+1 day') FROM days WHERE day < '2024-10-05'
)
SELECT day FROM days;
Returns
day
----------
2024-10-01
2024-10-02
2024-10-03
2024-10-04
2024-10-05
(5 rows)

PostgreSQL also has generate_series for this, and SQL Server writes WITH without the word RECURSIVE.

Practice

Each staff member's name and their manager's name, with NULL for Rosa.

The tables
  • customers (id, name, city, joined)
  • products (id, name, category, price)
  • orders (id, customer_id, ordered_on, status)
  • order_items (order_id, product_id, qty)
  • signups (id, email, name, signed_up_at)
  • payments (id, order_id, amount, currency, paid_at)
  • events (id, received_at, payload (JSON text))
  • staff (id, name, role, manager_id, salary, hired)
  • logins (customer_id, day)
More info

Quick reference

FROM t a JOIN t b ON …A self join: one table, two aliases.
WITH RECURSIVE x AS (start UNION ALL step)Repeat the step until it adds no rows.
depth + 1Track how many steps down.
date(day, '+1 day')A step that makes a calendar.

The other AI and data engineering courses