CREATE MATERIALIZED VIEW (Create Materialized View)
Last updated: 2026-11-04
CREATE MATERIALIZED VIEW (Create Materialized View)
CREATE MATERIALIZED VIEW materializes the result of a query into a real table on disk, trading space and write time for query speed. It suits reporting workloads that re-aggregate the same data over and over. A materialized view never updates on its own — after the base data changes you must run REFRESH MATERIALIZED VIEW.
| Kind | command |
|---|---|
| Example Language | SQL |
📝 Syntax
CREATE MATERIALIZED VIEW [IF NOT EXISTS] <materialized view name>
[(<column>, ...)]
AS <query>
[WITH [NO] DATA]
[TABLESPACE <tablespace name>]
⚙️ Parameters
| AS | The query that defines the materialized view |
|---|---|
| WITH DATA | Populate the view immediately (the default) |
| WITH NO DATA | Create the structure only and populate it later |
| TABLESPACE | The tablespace that holds the data |
Returns:No return value. Once it succeeds the materialized view is an independent, queryable relation.
▶ Example
Runs real PostgreSQL 18 right in your browser (PGlite WASM, nothing to install). Press ▶ Run and the result appears in the panel below.
Output:
DROP TABLE
DROP MATERIALIZED VIEW
CREATE TABLE
INSERT 0 3
CREATE MATERIALIZED VIEW
region | orders | total
-------+--------+-------
east | 2 | 350.50
west | 1 | 300.00
📌 Key Points
- A materialized view is an independent relation with its own file, so it can be indexed and queried like a table.
- WITH DATA is the default and populates immediately; WITH NO DATA creates only the structure, to be filled later by REFRESH ... WITH DATA.
- The contents are a snapshot taken at creation time; later changes to the base table are not reflected until you refresh.
- A refresh recomputes the whole query and swaps in the new result (except with CONCURRENTLY) while holding a lock.
- Using REFRESH ... CONCURRENTLY requires a unique index on the materialized view to exist first.
💡 Related Cases
More case studies coming soon.
📚 Related Reference
❓ FAQ
QWhen does a materialized view need a unique index?
AREFRESH MATERIALIZED VIEW CONCURRENTLY requires a unique index; without one it fails with cannot refresh materialized view ... concurrently.
QIs the data in a materialized view up to date?
ANo — it is a snapshot from creation or the last refresh. Run REFRESH MATERIALIZED VIEW to update it, usually on a schedule.