🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Introduction to Common Table Expressions

Common Table ExpressionsCTE BasicsđŸŸĸ Free Lesson
Common Table Expressions

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?

CTE PipelineWITH active_emp ASSELECT * FROM empWHERE active = 1Named result setWITH dept_stats ASSELECT dept, AVG(sal)FROM active_empReferences CTE aboveSELECT * FROMdept_stats JOINactive_emp ON ...Final queryResultdept | avgEng | 72k

CTEs were introduced in SQL:1999 and are supported by PostgreSQL, MySQL 8+, SQL Server, Oracle, and SQLite 3.8.3+.

CTE vs Subquery

FeatureCTEInline Subquery
ReadabilityHigh — named blocksLow — nested, hard to follow
ReusabilityCan reference multiple timesMust repeat the subquery
DebuggingEasy — test CTE independentlyDifficult — embedded in larger query
ScopeOnly within one queryOnly within one query
PerformanceOptimizer may inlineOptimizer 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

ClausePurposeExample
WITHBegins CTE definitionWITH cte AS (...)
RECURSIVEEnables self-referencingWITH RECURSIVE cte AS (...)
UNION ALLCombines base and recursive casesRequired in recursive CTEs
Column aliasesOptional namingWITH 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

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. 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

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. 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

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids 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
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Related Tutorials

Content with similar topics across other courses

Continue Learning

Suggested next tutorials based on this topic

Need Expert SQL Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement