← Back to SQL, page 6

sql-0109 · Hard senior

In PostgreSQL, what is the difference between a materialized and an inlined CTE, and when does it matter?

A materialized CTE is computed once and stored as a temporary result; the main query reads that result and filters cannot be pushed into it. An inlined CTE is merged into the main query like a subquery, so the planner can push filters down and use indexes. Since PostgreSQL 12, a side-effect-free CTE referenced once is inlined by default, and AS MATERIALIZED or AS NOT MATERIALIZED overrides the choice.

Full answer

Before PostgreSQL 12, every CTE was an "optimization fence": it was computed in full and the outer WHERE could not reach inside. Teams sometimes used that on purpose to control plans, and sometimes suffered from it when a CTE scanned a whole table only for the outer query to keep one row.

From version 12 the default changed. A CTE that is referenced once and has no side effects is inlined. You can see the difference in the plans:

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');
sql
EXPLAIN (COSTS OFF)
WITH e AS (SELECT * FROM employees)
SELECT name FROM e WHERE dept_id = 1;
text
Seq Scan on employees
  Filter: (dept_id = 1)
sql
EXPLAIN (COSTS OFF)
WITH e AS MATERIALIZED (SELECT * FROM employees)
SELECT name FROM e WHERE dept_id = 1;
text
CTE Scan on e
  Filter: (dept_id = 1)
  CTE e
    ->  Seq Scan on employees

The inlined plan applies the dept_id = 1 filter directly to the scan of employees. The materialized plan builds the full CTE result first (the CTE Scan over all departments' rows) and filters afterwards.

When materializing helps: the CTE is expensive and referenced several times (it is then computed once by default), or you need to stop the planner from choosing a bad plan that it keeps picking. When it hurts: a broad CTE followed by a selective outer filter, as above.

SQLite also decides per query whether to materialize or inline (it calls the latter "query flattening"), and accepts the same MATERIALIZED hints since 3.35.

sql
CREATE TABLE departments (
  id   INTEGER PRIMARY KEY,
  name TEXT NOT NULL
);
CREATE TABLE employees (
  id         INTEGER PRIMARY KEY,
  name       TEXT NOT NULL,
  dept_id    INTEGER REFERENCES departments(id),
  manager_id INTEGER REFERENCES employees(id),
  salary     INTEGER,
  hire_date  TEXT
);
INSERT INTO departments VALUES (1,'Engineering'),(2,'Sales'),(3,'Support'),(4,'Legal');
INSERT INTO employees VALUES
  (1,'Asha', 1,NULL,120000,'2019-03-01'),
  (2,'Ravi', 1,1,    95000,'2020-07-15'),
  (3,'Mei',  1,1,    95000,'2021-01-10'),
  (4,'Tom',  2,1,    70000,'2022-05-20'),
  (5,'Sara', 2,4,    62000,'2023-02-01'),
  (6,'Diego',3,1,    55000,'2021-11-30'),
  (7,'Lena', NULL,4, NULL,  '2024-06-03'),
  (8,'Omar', 3,6,    48000,'2024-09-09');

Checked on SQLite 3.46.1, run twice with identical output. PostgreSQL results in the answer were checked on PostgreSQL 17.12.

Key points

  • Materialized: computed once, outer filters cannot be pushed in
  • Inlined: merged into the main query, filters and indexes can be used
  • PostgreSQL 12+ inlines single-reference, side-effect-free CTEs by default
  • AS MATERIALIZED and AS NOT MATERIALIZED override the default

Common mistakes

  • Assuming CTEs are always an optimization fence, which was only true before PostgreSQL 12
  • Assuming CTEs are always inlined, even when referenced several times

Follow-ups

  • How would you check which version of a plan PostgreSQL chose?
  • When would you deliberately add AS MATERIALIZED?

Tips

  • Quote the version where the default changed