SQL Intermediate Lesson 7: Recursive CTEs – Org Charts and Date Series

SQL Intermediate Lesson 7: Recursive CTEs - Org Charts and Date Series 1

📎 This article includes 2 downloadable practice files ↓

⏱ 2 min read

📘 SQL Intermediate Course · Lesson 7 of 10

Advertisement
In this article
  1. Reporting paths
  2. A calendar from nothing
  3. Practice

A recursive CTE has two parts joined by UNION ALL: a starting row (the anchor) and a step that adds rows based on the previous ones, repeated until no new rows appear.

WITH RECURSIVE team(emp_id, name, lvl) AS (
  SELECT emp_id, name, 0 FROM employees WHERE emp_id = 2          -- anchor: Neha
  UNION ALL
  SELECT e.emp_id, e.name, t.lvl + 1
  FROM employees e JOIN team t ON e.manager_id = t.emp_id          -- step: her reports
)
SELECT * FROM team;

Reporting paths

WITH RECURSIVE p(emp_id, path) AS (
  SELECT emp_id, name FROM employees WHERE manager_id IS NULL
  UNION ALL
  SELECT e.emp_id, p.path || ' > ' || e.name FROM employees e JOIN p ON e.manager_id = p.emp_id
)
SELECT path FROM p;   -- Anil Kapoor > Neha Sharma > Arjun Mehta > Rohan Gill

A calendar from nothing

WITH RECURSIVE d(day) AS (
  SELECT '2026-07-01'
  UNION ALL
  SELECT date(day, '+1 day') FROM d WHERE day < '2026-07-31'
)
SELECT day FROM d WHERE day NOT IN (SELECT order_date FROM orders);

Calendars fill gaps for LAG (lesson 4) and zero-sales days in charts.

⚠️ Always include a stop condition (WHERE day < ...). A cycle in the data (A manages B, B manages A) loops until the database’s recursion limit.

Syntax: SQL Server and Oracle write WITH without RECURSIVE; string concatenation is + in SQL Server and CONCAT() in MySQL.

Practice

Download shop2.db and this lesson’s exercise file below. Open the database in DB Browser for SQLite (free), paste each task into the Execute SQL tab and compare with the expected result printed under it. Answers are at the bottom of the file.

📎 Practice files for this article

⬇ Download all 2 files (ZIP · 9 KB)

  • 📄
    Practice database (SQLite)shop2.db: customers, products, 300 orders, payments, employees with managers and monthly targets.
    ⬇ DB · 48 KB
  • 🗃️
    Lesson 7 exercisesTasks with the real expected result under each, and answers at the bottom.
    ⬇ SQL · 3 KB

Free to use for learning. Files with macros (.bas) are plain text — import them with Alt+F11 → File → Import File, and always test on a copy.

Advertisement
✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free · AI can be wrong