Bird
Raised Fist0
PostgreSQLquery~5 mins

CTE vs subquery performance in PostgreSQL - Quick Revision & Key Differences

Choose your learning style10 modes available
Recall & Review
beginner
What is a Common Table Expression (CTE) in SQL?
A CTE is a temporary named result set that you can reference within a SELECT, INSERT, UPDATE, or DELETE statement. It helps organize complex queries by breaking them into simpler parts.
Click to reveal answer
beginner
How does a subquery differ from a CTE?
A subquery is a query nested inside another query, often used inline. A CTE is defined before the main query and can be referenced multiple times, improving readability and sometimes performance.
Click to reveal answer
intermediate
Does PostgreSQL always optimize CTEs and subqueries the same way?
No. Before PostgreSQL 12, CTEs acted as optimization fences, meaning they were executed separately and results materialized. Subqueries could be inlined and optimized better. From PostgreSQL 12, CTEs can be inlined like subqueries unless marked with MATERIALIZED or NOT MATERIALIZED.
Click to reveal answer
intermediate
When might a CTE perform worse than a subquery?
If the CTE is materialized (executed and stored) and used only once, it can cause extra work and slower performance compared to a subquery that the planner can inline and optimize.
Click to reveal answer
beginner
What is one advantage of using CTEs despite potential performance costs?
CTEs improve query readability and maintainability by breaking complex queries into named parts. They also allow recursive queries, which subqueries cannot do.
Click to reveal answer
Before PostgreSQL 12, how were CTEs treated in terms of query optimization?
AThey acted as optimization fences and were materialized separately
BThey were always inlined and optimized with the main query
CThey were ignored by the query planner
DThey were automatically converted to subqueries
Which keyword forces a CTE to be materialized in PostgreSQL 12 and later?
AMATERIALIZED
BOPTIMIZE
CINLINE
DCACHE
Which of the following is a benefit of using subqueries over CTEs?
ABetter readability for complex queries
BAbility to write recursive queries
CPotentially better performance due to inlining
DNamed temporary result sets
What is a common reason to choose a CTE despite possible performance costs?
AThey always run faster than subqueries
BThey allow breaking queries into understandable parts
CThey reduce disk space usage
DThey automatically index the data
In PostgreSQL 12+, what happens if you do not specify MATERIALIZED or NOT MATERIALIZED for a CTE?
AThe query will fail
BThe CTE is always inlined if possible
CThe CTE is always materialized
DThe planner decides whether to inline or materialize
Explain the performance differences between CTEs and subqueries in PostgreSQL, especially before and after version 12.
Think about how the query planner treats CTEs and subqueries differently across versions.
You got /6 concepts.
    Describe when it might be better to use a subquery instead of a CTE for performance reasons.
    Consider how materialization affects execution time.
    You got /4 concepts.

      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