Sub topic 2
Creating a materialized view with `CREATE MATERIALIZED VIEW`
This chapter assumes that you know SELECT, GROUP BY, aggregate functions such as count and sum, and the difference between a table and a plain view. It also assumes that you can connect to PostgreSQL with psql or another SQL client.
A materialized view is a database object that stores the rows produced by a query. PostgreSQL runs the query when you create the object, then saves the result. You can query the materialized view like a table.
A plain view stores only a query definition. Each time you query the view, PostgreSQL runs that query against the current base tables. A materialized view stores both the query definition and its current result.
Creating the materialized view
Suppose an orders table contains one row per order. The following statement creates a materialized view with one row per order date:
CREATE TABLE orders (
id bigserial PRIMARY KEY,
customer_id integer NOT NULL,
order_date date NOT NULL,
total numeric(10,2) NOT NULL
);
INSERT INTO orders (customer_id, order_date, total)
VALUES
(1, DATE '2026-11-25', 25.00),
(2, DATE '2026-11-25', 40.50),
(1, DATE '2026-11-26', 12.75);
CREATE MATERIALIZED VIEW sales_daily AS
SELECT
order_date AS day,
count(*) AS orders,
sum(total) AS revenue
FROM orders
GROUP BY order_date;
SELECT *
FROM sales_daily
ORDER BY day;The final query reads stored rows from sales_daily. Its result is similar to this:
| day | orders | revenue |
|---|---|---|
| 2026-11-25 | 2 | 65.50 |
| 2026-11-26 | 1 | 12.75 |
The column names come from the query aliases. day comes from order_date AS day, and orders and revenue come from their aggregate aliases. Explicit aliases make the materialized view easier to use from application code.
The AS query can contain joins, filters, grouping, and other SQL that produces a result set. PostgreSQL evaluates that query during creation. The initial result is populated immediately unless you specify WITH NO DATA.
Choosing the object name and columns
You can provide an explicit column list after the materialized view name:
CREATE MATERIALIZED VIEW customer_totals (customer_id, lifetime_value) AS
SELECT
customer_id,
sum(total)
FROM orders
GROUP BY customer_id;The number of names in the list must match the number of columns returned by the query. Explicit names are useful when the query contains expressions without clear names.
A materialized view has a relation name and can be used in many read queries:
SELECT customer_id, lifetime_value
FROM customer_totals
WHERE lifetime_value >= 50.00;Although it behaves like a table for reads, it is maintained differently. You normally do not insert rows directly into a materialized view. You change the base tables, then refresh the materialized view so PostgreSQL recomputes its stored result.
Creating a view without running the query
For a large source table, the initial query may take a long time. WITH NO DATA creates the materialized view definition but skips the initial population:
CREATE MATERIALIZED VIEW customer_totals_empty AS
SELECT
customer_id,
sum(total) AS lifetime_value
FROM orders
GROUP BY customer_id
WITH NO DATA;The object exists, but it has no queryable contents until it is populated by a refresh. A later chapter explains how to check this state and populate the view.
A practical design check
Before creating a materialized view, run its query as a normal SELECT. Confirm that:
- Each output column has the intended name and data type.
- The grouping produces the level of detail your users need.
- Filters exclude only data that should not be included.
- The result is expensive or frequent enough to justify storing it.
Materialization trades freshness and storage for faster reads. The query should produce a useful reusable result, rather than merely duplicating a small table.
Exercise
What does PostgreSQL store when you run CREATE MATERIALIZED VIEW sales_daily AS SELECT ...?
Show answer
PostgreSQL stores the query definition and the rows produced by that query at creation time. Later SELECT statements read the stored rows until the materialized view is refreshed.