Mastering MySQL for Data AnalystsLesson 26 of 42
Lesson 26 of 42

Common Table Expressions (CTEs): WITH Clause in MySQL 8.0

Overview & Learning Objectives

As analytical questions grow complex, nested subqueries become an unreadable mess of parentheses known as "SQL spaghetti." MySQL 8.0 introduced Common Table Expressions (CTEs) via the `WITH` clause. A CTE defines a named temporary result set that exists only for the duration of a single query, allowing analysts to structure complex data transformations into clean, sequential, top-to-bottom pipelines.

  • Define single and chained Common Table Expressions using the `WITH` clause.
  • Refactor deeply nested subqueries into readable sequential CTE pipelines.
  • Understand how MySQL 8.0 optimizes CTE execution (inline merging vs materialization).

Industry Standard

Standard: Analytics engineering frameworks like dbt and Snowflake mandate CTEs at the top of every SQL model to enforce readability and self-documenting data lineage.

Real-World Example: ScoopCraft Two-Stage Customer Segmentation Pipeline

ScoopCraft computes store-level revenue benchmarks in CTE 1, and filters for high-performing stores in the main query.

CTE NamePipeline StageLogic ExecutedOutput Used By
store_metricsStage 1: AggregateCompute total revenue and order count per storeStage 2 & Main Query
store_benchmarksStage 2: BenchmarkCalculate national average revenue across storesMain Query Filter
Final SELECTStage 3: ReportingFilter stores exceeding national benchmarkExecutive Dashboard

Syntax & Core SQL Implementation

-- Modular Multi-CTE Analytics Pipeline in MySQL 8.0
WITH store_metrics AS (
    SELECT 
        dark_store,
        COUNT(order_id) AS total_orders,
        ROUND(SUM(order_total), 2) AS total_revenue
    FROM orders
    WHERE order_date >= '2026-01-01'
    GROUP BY dark_store
),
national_benchmark AS (
    SELECT 
        ROUND(AVG(total_revenue), 2) AS avg_store_rev
    FROM store_metrics
)
SELECT 
    sm.dark_store,
    sm.total_orders,
    sm.total_revenue,
    nb.avg_store_rev,
    ROUND(sm.total_revenue - nb.avg_store_rev, 2) AS variance
FROM store_metrics sm
CROSS JOIN national_benchmark nb
WHERE sm.total_revenue > nb.avg_store_rev
ORDER BY sm.total_revenue DESC;

Parameters & Arguments Breakdown

  • WITH cte_name AS (...): Defines the start of a Common Table Expression with a named temporary result set.
  • , next_cte AS (...): Chains additional CTEs separated by commas, referencing prior CTEs sequentially.
  • Final SELECT: The primary consuming query executed immediately following the CTE definitions.

Sample Walkthrough (Q&A)

Question: What are the main advantages of CTEs over nested subqueries in MySQL 8.0?

SQL Pattern: WITH cte AS (...) vs SELECT ... FROM (SELECT ...)

Result: Superior linear readability, self-documenting code, reusable named blocks, and easier step-by-step debugging

Explanation: CTEs read from top to bottom like procedural code, eliminating confusing inside-out nested parentheses.

Common Mistakes & Limitations

  • Placing a semicolon at the end of a CTE block before the final `SELECT`, terminating the statement prematurely and throwing a syntax error.
  • Repeating `WITH` for subsequent chained CTEs; separate multiple CTEs with commas (`WITH a AS (...), b AS (...)`).

Keyboard Shortcuts (MySQL Workbench)

ActionWindowsMac
Execute QueryCtrl + EnterCmd + Enter

Pro Tips & Modern Best Practices

  • In MySQL 8.0, the optimizer can either merge a CTE directly into the outer query or materialize it into an in-memory temporary table depending on cost.
  • Use CTEs to break 100-line monolithic queries into 3-4 bite-sized logical steps that junior analysts can easily understand and review.