Introduction to CTEs
Name temporary result sets to break complex queries into logical, readable steps.
- Readability â Replace nested subqueries with named, self-documenting blocks
- Reusability â Reference the same CTE multiple times in one query
- Modularity â Decompose logic into independent, testable pieces CTEs make SQL queries as readable as pseudocode.
What Is a CTE?
CTEs were introduced in SQL:1999 and are supported by PostgreSQL, MySQL 8+, SQL Server, Oracle, and SQLite 3.8.3+.
CTE vs Subquery
| Feature | CTE | Inline Subquery |
|---|---|---|
| Readability | High â named blocks | Low â nested, hard to follow |
| Reusability | Can reference multiple times | Must repeat the subquery |
| Debugging | Easy â test CTE independently | Difficult â embedded in larger query |
| Scope | Only within one query | Only within one query |
| Performance | Optimizer may inline | Optimizer may inline |
Basic Syntax
-- Simple CTE structure
WITH cte_name (column1, column2) AS (
-- CTE query definition
SELECT column1, column2
FROM source_table
WHERE condition
)
-- Main query referencing the CTE
SELECT *
FROM cte_name
ORDER BY column1;
Single CTE Example
-- Find all employees earning above the company average
WITH avg_salary AS (
SELECT AVG(salary) AS company_avg
FROM employees
)
SELECT
e.employee_name,
e.department,
e.salary,
a.company_avg,
ROUND(e.salary - a.company_avg, 2) AS diff_from_avg
FROM employees e
CROSS JOIN avg_salary a
WHERE e.salary > a.company_avg
ORDER BY e.salary DESC;
Chained CTEs
-- Multi-step transformation using chained CTEs
WITH
-- Step 1: Filter to active employees only
active_employees AS (
SELECT employee_id, employee_name, department, salary
FROM employees
WHERE status = 'Active'
),
-- Step 2: Calculate department statistics
dept_stats AS (
SELECT
department,
COUNT(*) AS dept_size,
AVG(salary) AS dept_avg,
MAX(salary) AS dept_max
FROM active_employees
GROUP BY department
),
-- Step 3: Combine employee data with department stats
combined AS (
SELECT
ae.employee_name,
ae.department,
ae.salary,
ds.dept_avg,
ds.dept_max,
ROUND(ae.salary - ds.dept_avg, 2) AS diff_from_dept_avg,
ROUND(ae.salary / ds.dept_max * 100, 1) AS pct_of_dept_max
FROM active_employees ae
JOIN dept_stats ds ON ae.department = ds.department
)
-- Final: Select and filter the results
SELECT *
FROM combined
WHERE diff_from_dept_avg > 0
ORDER BY department, salary DESC;
CTE for Aggregation
-- Department-level summary with CTE
WITH dept_summary AS (
SELECT
department,
COUNT(*) AS employee_count,
SUM(salary) AS total_salary,
AVG(salary) AS avg_salary,
MIN(salary) AS min_salary,
MAX(salary) AS max_salary
FROM employees
WHERE status = 'Active'
GROUP BY department
)
SELECT
department,
employee_count,
total_salary,
ROUND(avg_salary, 2) AS avg_salary,
min_salary,
max_salary,
ROUND(max_salary - min_salary, 2) AS salary_range
FROM dept_summary
WHERE employee_count >= 5
ORDER BY total_salary DESC;
CTE for Deduplication
-- Remove duplicate records keeping the latest entry
WITH ranked_records AS (
SELECT
*,
ROW_NUMBER() OVER (
PARTITION BY customer_id, product_id
ORDER BY created_at DESC
) AS rn
FROM order_items
)
SELECT
customer_id,
product_id,
quantity,
price,
created_at
FROM ranked_records
WHERE rn = 1;
CTE for Reporting
-- Sales report with category breakdown
WITH monthly_sales AS (
SELECT
DATE_FORMAT(sale_date, '%Y-%m') AS month,
category,
SUM(amount) AS total_sales,
COUNT(*) AS transaction_count
FROM sales
GROUP BY DATE_FORMAT(sale_date, '%Y-%m'), category
),
ranked_categories AS (
SELECT
month,
category,
total_sales,
transaction_count,
RANK() OVER (PARTITION BY month ORDER BY total_sales DESC) AS category_rank
FROM monthly_sales
)
SELECT
month,
category,
total_sales,
transaction_count,
category_rank
FROM ranked_categories
WHERE category_rank <= 3
ORDER BY month, category_rank;
Recursive CTE Preview
-- Employee hierarchy using recursive CTE (simplified)
WITH RECURSIVE org_chart AS (
-- Base case: top-level managers
SELECT employee_id, employee_name, manager_id, 1 AS level
FROM employees
WHERE manager_id IS NULL
UNION ALL
-- Recursive case: direct reports
SELECT e.employee_id, e.employee_name, e.manager_id, oc.level + 1
FROM employees e
JOIN org_chart oc ON e.manager_id = oc.employee_id
)
SELECT employee_id, employee_name, level
FROM org_chart
ORDER BY level, employee_name;
Quick Reference
| Clause | Purpose | Example |
|---|---|---|
WITH | Begins CTE definition | WITH cte AS (...) |
RECURSIVE | Enables self-referencing | WITH RECURSIVE cte AS (...) |
UNION ALL | Combines base and recursive cases | Required in recursive CTEs |
| Column aliases | Optional naming | WITH cte (a, b) AS (...) |
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type â Always start by categorizing the problem
- Incorrect formula application â Verify the formula applies to your specific case
- Unit errors â Always check units are consistent throughout
- Sign errors â Pay careful attention to positive and negative values
- Rounding too early â Keep full precision until the final answer
- Forgetting constraints â Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic â Build on the foundation laid here
- Next Topic â See how this concept extends to more advanced material
- Practice Problems â Additional exercises with solutions
- Video Explanation â Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions