Tutorials Courses Interview Prep (100 Q&A) AI Tools (50) Developer Tools (50) Tracks Pricing Plans Blog & Articles Contact Us
PostgreSQL Enterprise & Performance 8-10 Years (Tech Lead) Hard Production Scenario

Explain CTE Optimization Fencing (`AS MATERIALIZED` vs `AS NOT MATERIALIZED`) in PostgreSQL 12+.

Real-World Scenario / Incident Description

A complex query using Common Table Expressions ran 10x slower because the optimizer materialized intermediate result sets.

212 views • Updated 1 month ago

Controlling CTE Inlining

  • WITH my_cte AS NOT MATERIALIZED (...): Forces the query planner to inline the CTE directly into the parent query, allowing index pushdown and filter sharing.
  • WITH my_cte AS MATERIALIZED (...): Forces PostgreSQL to compute the CTE once into a temporary buffer, preventing repetitive recalculation if referenced multiple times.
Related Concepts: #CTE #MATERIALIZED #Query Optimizer