Common Table
Expressions (CTEs)
Master the WITH clause to break complex queries into readable, reusable building blocks that make your SQL clear and maintainable.
What Is a CTE?
A Common Table Expression (CTE) is a temporary, named result set that you define at the beginning of a query using the WITH keyword. It exists only for the duration of that single statement: once the query finishes, the CTE disappears.
Why CTEs Matter
Anatomy of WITH
The Basic Syntax
WITH high_scorers AS ( SELECT student_name, score FROM exam_results WHERE score >= 90 ) SELECT * FROM high_scorers ORDER BY score DESC;
CTE vs Subquery
| CTE (WITH) | Subquery | |
|---|---|---|
| Location | Defined before the main query | Nested inside the main query |
| Readability | High: named, top-down | Lower: deeply nested |
| Reuse | Can be referenced multiple times | Must be duplicated each time |
| Recursion | Supported | Not supported |
| Performance | Usually the same as subquery | Usually the same as CTE |
CTE vs Temp Table vs View
How to Write a CTE
How the Database Processes a CTE
Example 1: Simple CTE
Find all products with above-average prices.
WITH avg_price AS ( SELECT AVG(price) AS mean_price FROM products ) SELECT product_name, price FROM products, avg_price WHERE price > avg_price.mean_price;
Example 2: Multiple CTEs
Compare each department's total sales to the company average.
WITH dept_totals AS ( SELECT department, SUM(amount) AS total FROM sales GROUP BY department ), company_avg AS ( SELECT AVG(total) AS avg_total FROM dept_totals ) SELECT d.department, d.total, c.avg_total FROM dept_totals d, company_avg c WHERE d.total > c.avg_total;
Example 3: CTE with JOIN
Find customers who placed more orders than the average customer.
WITH order_counts AS ( SELECT customer_id, COUNT(*) AS num_orders FROM orders GROUP BY customer_id ) SELECT c.name, oc.num_orders FROM customers c JOIN order_counts oc ON c.id = oc.customer_id WHERE oc.num_orders > ( SELECT AVG(num_orders) FROM order_counts );
Recursive CTEs
A recursive CTE references itself to traverse hierarchical data: org charts, file trees, or category hierarchies. It has two parts joined by UNION ALL.
WITH RECURSIVE hierarchy AS ( -- Anchor: start at top-level SELECT id, name, manager_id, 1 AS depth FROM employees WHERE manager_id IS NULL UNION ALL -- Recursive: find direct reports SELECT e.id, e.name, e.manager_id, h.depth + 1 FROM employees e JOIN hierarchy h ON e.manager_id = h.id ) SELECT * FROM hierarchy;
How Recursion Unfolds
Common Mistakes
Summary Reference
| Feature | Syntax / Rule |
|---|---|
| Single CTE | WITH name AS ( SELECT ... ) |
| Multiple CTEs | WITH a AS (...), b AS (...) SELECT ... |
| Recursive CTE | WITH RECURSIVE name AS (anchor UNION ALL recursive) |
| Scope | Exists only for the one statement it precedes |
| Reuse | Can be referenced multiple times in the main query |
| Column aliases | Optional: WITH name(col1, col2) AS (...) |
| Nesting order | Later CTEs can reference earlier ones, but not the reverse |
Question 1 of 5
Which keyword introduces a Common Table Expression?
Question 2 of 5
How do you define multiple CTEs in a single query?
Question 3 of 5
What is the scope of a CTE?
Question 4 of 5
In a recursive CTE, what happens if you omit the anchor member?
Question 5 of 5
Given the query below, what does the CTE recent_orders contain?
WITH recent_orders AS ( SELECT * FROM orders WHERE order_date >= '2024-01-01' ) SELECT COUNT(*) FROM recent_orders;