Bird
Raised Fist0
PostgreSQLquery~10 mins

CTE vs subquery performance in PostgreSQL - Visual Side-by-Side Comparison

Choose your learning style10 modes available
Concept Flow - CTE vs subquery performance
Start Query
↓
Check for CTE or Subquery
↓
Materialize?
↓
Use Result
↓
Return Final Result
The query starts, checks if it uses a CTE or subquery, executes accordingly, possibly materializing CTE results, then returns the final output.
Execution Sample
PostgreSQL
WITH cte AS (
  SELECT * FROM orders WHERE amount > 100
)
SELECT * FROM cte WHERE customer_id = 1;
This query uses a CTE to filter orders with amount > 100, then selects those for customer_id 1.
Execution Table
StepActionEvaluationResult
1Start query executionWITH clause foundPrepare CTE execution
2Execute CTE querySELECT * FROM orders WHERE amount > 100Filtered rows with amount > 100
3Materialize CTE resultStore filtered rowsCTE result stored in memory
4Execute outer querySELECT * FROM cte WHERE customer_id = 1Filter CTE rows by customer_id
5Return final resultRows matching both conditionsFinal filtered rows returned
6EndNo more stepsQuery complete
💡 Query ends after returning filtered rows from CTE
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
CTE Resultemptyfiltered orders > 100stored in memoryfiltered by customer_id=1final filtered rows
Key Moments - 2 Insights
Why does the CTE sometimes cause slower performance than a subquery?
Because in PostgreSQL, CTEs are often materialized (stored) before the outer query runs, as shown in step 3 of the execution_table, which can add overhead compared to subqueries that are inlined.
Does a subquery always run faster than a CTE?
Not always. Subqueries can be optimized and inlined by the planner, avoiding materialization, but complex queries or repeated use of the same CTE can make CTEs more efficient.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, at which step is the CTE result materialized?
AStep 3
BStep 2
CStep 4
DStep 5
💡 Hint
Check the 'Action' and 'Result' columns in step 3 for materialization details.
According to variable_tracker, what is the state of 'CTE Result' after step 4?
Aempty
Bstored in memory
Cfiltered by customer_id=1
Dfiltered orders > 100
💡 Hint
Look at the 'After Step 4' column for 'CTE Result' in variable_tracker.
If the CTE was replaced by a subquery, which step might be skipped?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Materialization (step 3) is typical for CTEs but often skipped for subqueries.
Concept Snapshot
CTE vs Subquery Performance in PostgreSQL:
- CTEs often materialize results before outer query runs.
- Subqueries are usually inlined and optimized.
- Materialization can slow queries if large data sets.
- Use CTEs for readability or repeated use.
- Use subqueries for potential performance gains.
Full Transcript
This visual execution shows how PostgreSQL handles queries with CTEs versus subqueries. The query starts by detecting a CTE, executes the inner query filtering orders with amount greater than 100, then materializes the result in memory. After that, the outer query filters these results by customer_id. This materialization step can add overhead compared to subqueries, which are often inlined and optimized without storing intermediate results. The variable tracker shows how the CTE result changes state through execution. Key moments clarify why CTEs can be slower and when subqueries might be better. The quiz tests understanding of materialization and variable states during execution.

Practice

(1/5)
1. What is a common performance difference between CTEs and subqueries in PostgreSQL before version 12?
easy
A. CTEs and subqueries have identical performance.
B. Subqueries always run slower than CTEs.
C. CTEs act as optimization fences, potentially slowing queries.
D. Subqueries cannot be used inside SELECT statements.

Solution

  1. Step 1: Understand CTE behavior in PostgreSQL before v12

    CTEs are treated as optimization fences, meaning the planner executes them separately and does not optimize across them.
  2. Step 2: Compare with subqueries

    Subqueries can be inlined and optimized with the rest of the query, often leading to better performance.
  3. Final Answer:

    CTEs act as optimization fences, potentially slowing queries. -> Option C
  4. Quick Check:

    CTEs before v12 block optimization = A [OK]
Hint: Remember: CTEs block optimization before PostgreSQL 12 [OK]
Common Mistakes:
  • Thinking subqueries are always slower
  • Assuming CTEs and subqueries perform the same
  • Believing subqueries can't be inside SELECT
2. Which of the following is the correct syntax to define a CTE in PostgreSQL?
easy
A. WITH cte_name AS (SELECT * FROM table_name) SELECT * FROM cte_name;
B. SELECT * FROM table_name WITH cte_name AS ();
C. CREATE CTE cte_name SELECT * FROM table_name;
D. WITH (SELECT * FROM table_name) AS cte_name SELECT * FROM cte_name;

Solution

  1. Step 1: Recall CTE syntax

    CTEs start with WITH, followed by the CTE name, AS, and a query in parentheses.
  2. Step 2: Validate each option

    WITH cte_name AS (SELECT * FROM table_name) SELECT * FROM cte_name; matches the correct syntax. Options A, B, and C have incorrect order or keywords.
  3. Final Answer:

    WITH cte_name AS (SELECT * FROM table_name) SELECT * FROM cte_name; -> Option A
  4. Quick Check:

    CTE syntax starts with WITH name AS (query) [OK]
Hint: CTE syntax always starts with WITH name AS (query) [OK]
Common Mistakes:
  • Placing WITH after SELECT
  • Using CREATE keyword for CTE
  • Misplacing parentheses
3. Given the following queries, which one is likely to run faster in PostgreSQL 11?

-- Query 1 (CTE):
WITH recent_orders AS (SELECT * FROM orders WHERE order_date > '2024-01-01')
SELECT customer_id, COUNT(*) FROM recent_orders GROUP BY customer_id;

-- Query 2 (Subquery):
SELECT customer_id, COUNT(*) FROM (SELECT * FROM orders WHERE order_date > '2024-01-01') AS recent_orders GROUP BY customer_id;
medium
A. Query 1 runs faster because CTEs are always optimized.
B. Query 2 runs faster because subqueries allow better optimization in PostgreSQL 11.
C. Both queries run at the same speed.
D. Query 1 will cause a syntax error.

Solution

  1. Step 1: Understand PostgreSQL 11 optimization

    In PostgreSQL 11, CTEs act as optimization fences, so Query 1 executes the CTE separately.
  2. Step 2: Compare with subquery behavior

    Subqueries can be inlined and optimized with the main query, so Query 2 can be faster.
  3. Final Answer:

    Query 2 runs faster because subqueries allow better optimization in PostgreSQL 11. -> Option B
  4. Quick Check:

    PostgreSQL 11: subqueries optimize better than CTEs [OK]
Hint: Before v12, subqueries usually run faster than CTEs [OK]
Common Mistakes:
  • Assuming CTEs always optimize well
  • Thinking both queries have same speed
  • Believing Query 1 has syntax error
4. Identify the error in this query using a CTE in PostgreSQL:

WITH recent_orders AS SELECT * FROM orders WHERE order_date > '2024-01-01'
SELECT * FROM recent_orders;
medium
A. Missing parentheses around the CTE query.
B. CTE name is invalid.
C. Missing semicolon after CTE.
D. CTEs cannot filter by date.

Solution

  1. Step 1: Check CTE syntax

    CTE query must be enclosed in parentheses after AS keyword.
  2. Step 2: Identify the missing parentheses

    The query lacks parentheses around SELECT * FROM orders WHERE ...
  3. Final Answer:

    Missing parentheses around the CTE query. -> Option A
  4. Quick Check:

    CTE query must be in parentheses [OK]
Hint: Always put CTE query inside parentheses after AS [OK]
Common Mistakes:
  • Omitting parentheses around CTE query
  • Thinking semicolon is required after CTE
  • Believing CTE names can't be simple
5. You want to optimize a complex query in PostgreSQL 13 that uses multiple CTEs and subqueries. Which approach is best to improve performance?
hard
A. Avoid both CTEs and subqueries; use temporary tables instead.
B. Replace all CTEs with subqueries to allow better optimization.
C. Use only CTEs because subqueries are deprecated in PostgreSQL 13.
D. Keep CTEs because PostgreSQL 13 can inline them, improving speed.

Solution

  1. Step 1: Understand PostgreSQL 13 CTE behavior

    Starting with PostgreSQL 12, CTEs can be inlined and optimized like subqueries.
  2. Step 2: Evaluate optimization strategies

    Replacing CTEs with subqueries is not necessary; keeping CTEs maintains readability and performance.
  3. Final Answer:

    Keep CTEs because PostgreSQL 13 can inline them, improving speed. -> Option D
  4. Quick Check:

    PostgreSQL 12+ inlines CTEs for better optimization [OK]
Hint: PostgreSQL 12+ optimizes CTEs like subqueries [OK]
Common Mistakes:
  • Thinking subqueries are deprecated
  • Replacing CTEs blindly without testing
  • Assuming temporary tables always improve speed
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard