Video in progress
Is a CTE (WITH) faster or slower than a subquery?
Since PostgreSQL 12, a plain CTE is merged into the main query and optimized like a subquery, so the speed is the same. Before 12, a CTE was always computed separately and filters weren't pushed inside. Now you control this yourself with MATERIALIZED / NOT MATERIALIZED.
📖 Answer
In old articles you'll run into the phrase "CTE optimization fence". In PostgreSQL 11 and earlier, the WITH part was executed completely separately:
WITH recent AS (
SELECT * FROM orders WHERE created_at > now() - interval '1 year'
)
SELECT * FROM recent WHERE customer_id = 42;
On the old versions this gathered all of a year's orders and only then looked for customer 42, so the customer_id index wasn't used. In 12+ the planner pushes the customer_id = 42 condition inside and the index works.
There are cases where it isn't inlined: if the CTE is used twice in the query, if it's recursive, or if it contains INSERT/UPDATE/DELETE, it is materialized once.
Sometimes materialization is actually useful, to do a heavy calculation once and reuse the result:
WITH stats AS MATERIALIZED (
SELECT customer_id, sum(amount) AS total FROM orders GROUP BY customer_id
)
SELECT ...
In practice I write a CTE for readability, and on speed I trust only EXPLAIN ANALYZE. Another handy side is the data-modifying CTE: in one query you can delete rows and write them to an archive table (WITH moved AS (DELETE ... RETURNING *) INSERT INTO archive SELECT * FROM moved).
Sign up to mark studied questions and save your progress.