CTEs — Common Table Expressions
Give a name to a temporary result set and reference it like a table — making complex queries dramatically more readable.
A CTE is like a named building block. Write it once at the top, use it as many times as you need below.
EXERCISE
1CTEs — Naming Your Subqueries for Clarity
A Common Table Expression gives a name to a temporary result set. Instead of burying a subquery inside FROM, you define it up top and reference it like a table.
CTE syntax:
WITH cte_name AS (
SELECT ... -- your subquery here
)
SELECT * FROM cte_name; -- use it like a table
CTE vs subquery — same result, very different readability:
-- ❌ With a buried subquery — hard to read:
SELECT department, avg_sal
FROM (
SELECT department, AVG(salary) AS avg_sal
FROM employees
GROUP BY department
) AS dept_avg
WHERE avg_sal > 65000;
-- ✅ With a CTE — reads like a story:
WITH dept_avg AS (
SELECT department, AVG(salary) AS avg_sal
FROM employees
GROUP BY department
)
SELECT department, avg_sal
FROM dept_avg
WHERE avg_sal > 65000;
Multiple CTEs — chain them:
WITH
-- Step 1: get IT employees
it_employees AS (
SELECT e.name, e.salary
FROM employees e
JOIN departments d ON e.department_id = d.id
WHERE d.name = 'IT'
),
-- Step 2: compute IT average (using step 1)
it_stats AS (
SELECT AVG(salary) AS avg_sal, MAX(salary) AS max_sal
FROM it_employees
)
-- Step 3: find IT employees above IT average
SELECT e.name, e.salary, s.avg_sal
FROM it_employees e
CROSS JOIN it_stats s
WHERE e.salary > s.avg_sal;
CTEs can reference earlier CTEs in the same WITH block. This makes complex multi-step logic readable and maintainable.
Pro Tip: Use CTEs whenever a subquery would need to be repeated, or when nesting subqueries more than one level deep. The WITH clause makes SQL read almost like a recipe — step 1, step 2, step 3.
EXERCISE
2Recursive CTEs — Querying Hierarchical Data
A recursive CTE calls itself repeatedly to walk through hierarchical structures like org charts, category trees, or bill-of-materials.
A recursive CTE has two parts: an anchor (starting point) and a recursive member (each step down the hierarchy).
Syntax:
WITH RECURSIVE cte_name AS (
-- Anchor: the starting row(s)
SELECT ...
UNION ALL
-- Recursive member: join back to cte_name
SELECT ... FROM table JOIN cte_name ON ...
)
SELECT * FROM cte_name;
Example — walking an org chart from the top:
-- employees: id, name, manager_id (NULL for top-level)
WITH RECURSIVE org_chart AS (
-- Anchor: start with the CEO (no manager)
SELECT id, name, manager_id, 0 AS level, name AS path
FROM employees
WHERE manager_id IS NULL
UNION ALL
-- Recursive: find each employee's direct reports
SELECT e.id, e.name, e.manager_id,
oc.level + 1,
CONCAT(oc.path, ' → ', e.name)
FROM employees e
JOIN org_chart oc ON e.manager_id = oc.id
)
SELECT level, name, path
FROM org_chart
ORDER BY path;
Output:
+-------+----------+------------------------------+
| level | name | path |
+-------+----------+------------------------------+
| 0 | Vinay | Vinay |
| 1 | Awadhesh | Vinay → Awadhesh |
| 2 | Rituraj | Vinay → Awadhesh → Rituraj |
| 1 | Nevendra | Vinay → Nevendra |
+-------+----------+------------------------------+
Practical: generate a number series:
WITH RECURSIVE numbers AS (
SELECT 1 AS n
UNION ALL
SELECT n + 1 FROM numbers WHERE n < 10
)
SELECT n FROM numbers;
-- Output: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Pro Tip: Recursive CTEs are the right tool for any self-referencing table — org charts, product category trees, threaded comments. Without them, you would need multiple queries or application-level code.
EXERCISE
3CTEs vs Subqueries vs Temporary Tables
Three tools solve similar problems — knowing which one to reach for depends on complexity, reuse, and performance needs.
Quick comparison:
| Subquery | CTE | Temp Table | |
|---|---|---|---|
| Syntax | Inline in query | WITH clause | CREATE TEMPORARY TABLE |
| Reusable in same query | No (repeat it) | Yes (reference by name) | Yes |
| Persists across queries | No | No | Yes (for the session) |
| Indexable | No | No | Yes |
| Supports recursion | No | Yes | No |
| Performance (small data) | Fast | Fast | Similar |
| Performance (large data) | Can be slow if repeated | Can be slow if repeated | Fast (indexed) |
When to use each:
-- Use a SUBQUERY for simple, one-off inline calculations:
SELECT name FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
-- Use a CTE for multi-step logic or when the same subquery would repeat:
WITH avg_salary AS (SELECT AVG(salary) AS avg FROM employees)
SELECT name, salary, avg
FROM employees, avg_salary
WHERE salary > avg;
-- Use a TEMP TABLE when you need to query the result multiple times
-- or when you need to add an index for performance:
CREATE TEMPORARY TABLE dept_stats AS
SELECT department_id, AVG(salary) AS avg_sal FROM employees GROUP BY department_id;
CREATE INDEX idx_dept ON dept_stats (department_id);
-- Now join dept_stats multiple times without recomputing
CTE for delete duplicate records (practical pattern):
WITH ranked AS (
SELECT id,
ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) AS rn
FROM customers
)
DELETE FROM customers
WHERE id IN (SELECT id FROM ranked WHERE rn > 1);
-- Keeps the first occurrence of each email, deletes the rest
Pro Tip: Default to CTEs for readability. Switch to temporary tables only when performance profiling shows the CTE result is being recomputed expensively multiple times.
