← Learning Hub
Advanced

Common Table Expressions (WITH)

A CTE gives a name to a subquery at the top of your query with WITH. Long queries become a set of clear, readable steps.

A CTE (WITH clause) gives a name to a step of your query, so a long query reads like a recipe: first find monthly totals, then compare them, then pick the best. It makes complex SQL much easier to write, read and debug.

Example
WITH order_value AS (
  SELECT order_id, SUM(qty * price) AS total
  FROM order_items
  GROUP BY order_id
),
customer_value AS (
  SELECT o.customer_id, COUNT(*) AS orders, SUM(v.total) AS spent
  FROM orders o JOIN order_value v ON v.order_id = o.id
  WHERE o.status <> 'cancelled'
  GROUP BY o.customer_id
)
SELECT c.name, cv.orders, cv.spent
FROM customer_value cv JOIN customers c ON c.id = cv.customer_id
ORDER BY cv.spent DESC;

-- Result:
-- name        | orders | spent
-- ------------+--------+------
-- Ravi Kumar  | 2      | 4297
-- Asha Verma  | 3      | 4191
-- Arjun Mehta | 1      | 2097
-- Fatima Khan | 1      | 848
▶ Try it yourself

Recursive CTEs

A CTE can refer to itself. This is used for trees (categories inside categories, managers and employees) and for making number or date lists.

Example
WITH RECURSIVE days(d) AS (
  SELECT '2026-11-01'
  UNION ALL
  SELECT date(d, '+1 day') FROM days WHERE d < '2026-11-05'
)
SELECT d FROM days;

-- Result:
-- d
-- ----------
-- 2026-11-01
-- 2026-11-02
-- 2026-11-03
-- 2026-11-04
-- 2026-11-05
▶ Try it yourself
CTEs are great for interviews too: say what each step does, build it one CTE at a time, and run each part to check it.
Key points
  • WITH name AS (SELECT ...) defines a named step.
  • Later steps can use earlier ones.
  • Recursive CTEs walk trees like categories.

📝 Test yourself

1. Which keyword starts a CTE?
2. What are recursive CTEs often used for?
3. Fill in the keyword that lets a CTE refer to itself:
WITH days(d) AS (...)