SQL Tutorial 0/85 lessons ~6 min read Lesson 33

    Common Table Expressions (CTE)

    A CTE (WITH … AS (…)) is a named, in-query temporary result.

    Course progress0%
    Focus
    13 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    A CTE (WITH … AS (…)) is a named, in-query temporary result. CTEs make complex queries readable by breaking them into named steps. Postgres also supports recursive CTEs for tree/graph traversal.

    Learning objective: Apply Common Table Expressions (CTE) correctly in a TechLearningPRO production database — with clear query intent, safe defaults, and failure modes you can explain in review.

    Treat every example as production-shaped SQL: explicit column lists, deterministic predicates, and indexes that match the access path. Prefer PostgreSQL dialect notes when dialects diverge; call out MySQL differences when they matter.

    Purpose of this lesson

    Apply Common Table Expressions (CTE) correctly in a TechLearningPRO production database — with clear query intent, safe defaults, and failure modes you can explain in review.

    Understanding the topic

    Core concepts to understand:

    • WITH paid AS (SELECT ... FROM orders WHERE status='paid') SELECT ... FROM paid;
    • Multiple CTEs separated by commas.
    • Recursive CTE: WITH RECURSIVE tree AS (...).
    • Treat them as named subqueries — cleaner and reusable.
    • Modern optimizers inline non-recursive CTEs.

    Step-by-step explanation

    1. State the business question Common Table Expressions (CTE) answers and the tables involved.
    2. Read the workflow diagram and map each stage to parser, optimizer, or storage.
    3. Write the smallest correct statement (or design change) for a TechLearningPRO Orders/learners dataset.
    4. Predict the failure mode: wrong cardinality, missing index, or unsafe write — then verify.

    Syntax reference

    Visual workflow / architecture:

    bash
    WITH
    paid AS (
    SELECT * FROM orders WHERE status = 'paid'
    ),
    totals AS (
    SELECT user_id, sum(amount) AS spend FROM paid GROUP BY user_id
    )
    SELECT u.email, t.spend
    FROM users u JOIN totals t ON t.user_id = u.id
    WHERE t.spend > 1000;

    Informative example

    Shape to practice: rewrite the diagram as an explicit SQL statement against orders(id, learner_id, status, amount_cents, created_at) — select only the columns you need.

    sql
    -- TechLearningPRO Orders sketch for: Common Table Expressions (CTE)
    SELECT id, status, amount_cents
    FROM orders
    WHERE status = 'PENDING'
    ORDER BY created_at DESC
    LIMIT 50;

    Real-world use

    Analytics, reporting and ETL queries are almost always written as CTE pipelines for clarity. Recursive CTEs power org charts, threaded comments and graph traversal.

    Security implications

    SQL is a trust boundary. Application code must never concatenate untrusted input into statements.

    • Use bind parameters / prepared statements — never string-built SQL from request bodies.
    • Least-privilege DB roles: app users should not own DDL in production.
    • Avoid returning raw DB errors to clients; log server-side with a correlation id.

    Best practices

    • Refactor any query > 30 lines into CTEs.
    • Name CTEs after the meaning, not the table.
    • Use recursive CTEs for trees with care (depth limits).

    Common mistakes

    • Selecting * in application queries and shipping wide rows over the network.
    • Filtering on expressions that defeat indexes (WHERE YEAR(created_at) = 2026).
    • Running unbounded deletes/updates without a dry-run SELECT first.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    5 questions
    1BeginnerQuestionQ1. CTE vs subquery.+

    Answer

    CTEs name intermediate results.
    2IntermediateQuestionQ2. Show a recursive CTE.+

    Answer

    They make complex queries readable.
    3IntermediateQuestionQ3. Are CTEs always materialized?+

    Answer

    Recursive CTEs traverse trees and graphs.
    4AdvancedQuestionQ4. Multiple CTEs syntax.+

    Answer

    Recursive CTEs traverse trees and graphs.
    5AdvancedQuestionQ5. When to use a CTE over a temp table.+

    Answer

    Recursive CTEs traverse trees and graphs.

    Hands-on exercise

    Hands-on + interview drill:

    • Implement the smallest correct example for Common Table Expressions (CTE) on an Orders-like schema.
    • Q1. CTE vs subquery.
    • Q2. Show a recursive CTE.
    • Q3. Are CTEs always materialized?
    • Q4. Multiple CTEs syntax.
    • Q5. When to use a CTE over a temp table.

    Summary

    Common Table Expressions (CTE) is a production SQL skill: state the question, write the precise statement, and prove it with an execution plan or constraint — not with lucky result sets.

    Ready to mark this lesson complete?Track your journey across the entire course.