Skip to content
Back to 50 Concepts
Topic 37 of 50architectureIntermediate

# Topic 37: CTE (Common Table Expressions)

WITH clauses, modular query pipelines, CTE optimization fencing in PostgreSQL, and recursive CTE introduction.

1. Definition

A Common Table Expression (CTE) is a temporary named result set defined within the execution scope of a single SELECT, INSERT, UPDATE, or DELETE statement using the WITH keyword.

Relational Invariant:Deterministic relational algebra contract evaluated by the Cost-Based Optimizer.

2. Explain Like I'm 5

Intuitive mental model for beginners

A CTE is like writing down intermediate numbers on a scratchpad while solving a big math problem: you calculate Step A, name it, and use that named result in Step B.

3. Animation & Visual Simulation

Interactive Engine Trace
Interactive Engine Simulation

CTE (Common Table Expressions) Visual Simulator

Step 1 of 3
SQL>WITH active_users AS ( SELECT id, email FROM users WHERE status = 'active' ) SELECT COUNT(*) FROM active_users;Active Input

Step 1: Input & Parsing Stage

Engine Action: Validate SQL syntax and resolve schema metadata for CTE (Common Table Expressions)
SQL Input

Initiating CTE (Common Table Expressions)

Schema Catalog

Checking Table Invariants

How the Database Executes This:

The database engine inspects active tables, verifies permissions, and prepares the physical operation.

💡 Scratchpad: Writing down intermediate calculations with labels so you can combine them cleanly in the final formula.

4. Real-World Example

Calculating top sales representatives in each region and joining them with company benchmarks.

Modular Pipeline
CTE NamePurpose
regional_salesAggregates total revenue per sales rep and region
regional_averagesComputes benchmark average revenue per region
Relational walkthrough: The main query joins regional_sales with regional_averages cleanly.

5. SQL Syntax

ANSI SQL / PostgreSQL Dialect
Step 1: Multi-CTE pipeline
WITH regional_sales AS (
  SELECT region, rep_id, SUM(amount) AS total_sales
  FROM sales
  GROUP BY region, rep_id
),
regional_benchmarks AS (
  SELECT region, AVG(total_sales) AS avg_sales
  FROM regional_sales
  GROUP BY region
)
SELECT s.rep_id, s.region, s.total_sales, b.avg_sales
FROM regional_sales s
JOIN regional_benchmarks b ON s.region = b.region
WHERE s.total_sales > b.avg_sales;
Modular, top-to-bottom readable query structure.

6. Important Rules & Behaviors

RuleBehavioral Explanation
Scope LimitationA CTE only exists for the duration of the query in which it is declared.
Multiple CTEsDeclare multiple CTEs separated by commas under a single WITH keyword.
PostgreSQL 12+ InliningBy default, modern PostgreSQL inlines CTEs like subqueries unless explicitly declared AS MATERIALIZED.
PostgreSQL optimization fence behaviorPrior to PG 12, CTEs were always materialized (optimization fence); PG 12+ inlines CTEs unless marked AS MATERIALIZED.
CTE scope and lifetimeA CTE exists only for the duration of the single query statement in which it is defined; it cannot be queried in subsequent transactions.

7. Deep Dive: CTE Optimization Fencing: MATERIALIZED vs NOT MATERIALIZED

Prior to PostgreSQL 12, CTEs acted as rigid optimization fences: the engine calculated the entire CTE once, cached it in memory, and prevented the optimizer from pushing outer WHERE filters down into it. PostgreSQL 12+ inlines CTEs automatically.

-- Force PostgreSQL to materialize once:
WITH heavy_calc AS MATERIALIZED (
  SELECT id, complex_func(data) AS score FROM large_table
)
SELECT * FROM heavy_calc WHERE score > 50;

-- Force inlining so outer filters push down:
WITH raw_data AS NOT MATERIALIZED (
  SELECT * FROM transactions
)
SELECT * FROM raw_data WHERE user_id = 42; -- Pushes user_id = 42 into B-Tree index!
Caution: Use AS MATERIALIZED intentionally if a CTE contains a volatile calculation you want evaluated only once.

8. Advantages & Disadvantages

Advantages

  • •Dramatically improves readability over deeply nested subqueries.
  • •Can be referenced multiple times within the same query.

Disadvantages & Trade-offs

  • •In older PostgreSQL (<12), CTEs acted as optimization fences, slowing down queries.

9. Common Interview Questions

Q1.What is an "Optimization Fence" in PostgreSQL Common Table Expressions (CTEs)?

Historically in PostgreSQL (versions 11 and older), every CTE was treated as an optimization fence: the engine computed the entire CTE in memory (materialization) before running the outer query, preventing the optimizer from pushing WHERE filters or index constraints down into the CTE. In PostgreSQL 12+, CTEs are automatically inlined into the main query plan unless explicitly marked WITH cte AS MATERIALIZED (...).

Q2.What are the advantages of CTEs over nested derived table subqueries?

1. Readability: CTEs structure queries linearly from top to bottom instead of deep inside-out nesting. 2. Reusability: A single CTE can be referenced multiple times in the same query (e.g. joined against itself). 3. Recursive queries: CTEs support the RECURSIVE keyword for traversing hierarchical graphs, organizational trees, and bill-of-materials. 4. Writable CTEs: In PostgreSQL, CTEs can contain INSERT/UPDATE/DELETE with RETURNING.

Q3.What is a Writable (Data-Modifying) CTE in PostgreSQL and how is it used in production?

PostgreSQL allows INSERT, UPDATE, and DELETE statements inside a CTE with a RETURNING clause. This enables atomic data movement between tables in a single statement without multi-step procedural transactions: WITH moved_rows AS (DELETE FROM active_orders WHERE status = 'archived' RETURNING *) INSERT INTO order_archives SELECT * FROM moved_rows;

Q4.When should you explicitly specify WITH ... AS MATERIALIZED in PostgreSQL 12+?

You specify AS MATERIALIZED when: 1. The CTE is computationally expensive and referenced multiple times in the outer query (preventing the engine from re-evaluating it twice), 2. You intentionally want an optimization fence to prevent the planner from choosing a bad join order or risky plan transformation.

Q5.Can you update or delete rows through a CTE in PostgreSQL?

You cannot directly execute UPDATE cte_name SET ... because a CTE is a transient virtual result set. However, you can join the underlying physical table to the CTE in an UPDATE statement: WITH target_users AS (SELECT id FROM users WHERE inactive_days > 90) UPDATE users SET status = 'inactive' WHERE id IN (SELECT id FROM target_users);

10. Interview-Ready Answer

“Common Table Expressions (CTEs) define named, modular result sets using the WITH keyword. They turn deeply nested subqueries into readable top-to-bottom pipelines, and modern engines inline them to enable full optimizer index pushdowns.”

11. Quick Test

Scenario Question:

Which keyword is used to declare a Common Table Expression in SQL?

Select your answer: