Sub topic 2
Creating a materialized view with CREATE MATERIALIZED VIEW
This chapter assumes you can write SELECT queries with JOIN and GROUP BY, know that a plain view is a saved query, and have a PostgreSQL server and psql available. It covers the creation command: its syntax, what happens when it runs, and the rules the new object follows. Refreshing, indexing, and scheduling each get their own chapter, so they appear here only where they affect creation.
What the command does
CREATE MATERIALIZED VIEW does two things in one statement:
- It records the definition: a name, a column list, and the query text.
- It runs the query once and writes the result rows into storage owned by the new object.
After the statement finishes, the view is a relation with its own data files, much like a table. Queries against it read the stored rows. They do not re-run the original query.
Setting up sample data
The examples use an orders table. Run this first so the later queries return rows.
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)
SELECT (random() * 99)::int + 1,
CURRENT_DATE - (random() * 89)::int,
round((random() * 200 + 5)::numeric, 2)
FROM generate_series(1, 5000);This creates 5,000 orders spread over roughly the last 90 days for about 100 customers.
The basic form
The simplest statement names the view and supplies a query.
CREATE MATERIALIZED VIEW sales_daily AS
SELECT order_date AS day,
count(*) AS orders,
sum(total) AS revenue
FROM orders
GROUP BY order_date;The query runs immediately, so on a large table this statement can take as long as the query itself. When it finishes, you can read the view like a table:
SELECT * FROM sales_daily ORDER BY day DESC LIMIT 7;Each of the up to 90 rows holds one day's order count and revenue. The GROUP BY work was done once, at creation.
Confirming what you created
pg_class records the kind of each relation. A materialized view has relkind = 'm', where a table has 'r' and a plain view has 'v'.
SELECT relname, relkind
FROM pg_class
WHERE relname IN ('orders', 'sales_daily');You should see r for orders and m for sales_daily. In psql, \dm lists materialized views and \d+ sales_daily shows its columns, storage, and definition.
The full syntax
The general form, with every optional clause, is:
CREATE MATERIALIZED VIEW [ IF NOT EXISTS ] view_name
[ (column_name [, ...]) ]
[ USING access_method ]
[ WITH (storage_parameter [= value] [, ...]) ]
[ TABLESPACE tablespace_name ]
AS query
[ WITH [ NO ] DATA ];| Clause | Purpose | Default |
|---|---|---|
| `IF NOT EXISTS` | Skips creation with a notice if a relation of that name exists. | Error if the name is taken |
| `(column_name, ...)` | Names the view's columns, overriding names from the query. | Names come from the query |
| `USING access_method` | Chooses the table access method for storage. | `heap` (or `default_table_access_method`) |
| `WITH (storage_parameter)` | Sets storage options such as `fillfactor`. | Standard table defaults |
| `TABLESPACE` | Places the data files in a given tablespace. | The database default |
| `WITH [ NO ] DATA` | Controls whether the query runs now. | `WITH DATA` |
Most views use only the name and the query. The sections below cover the clauses that matter in practice.
Naming columns
Column names normally come from the query. A plain column keeps its name, and an aliased expression takes its alias. An expression with no alias gets a generic name like count or sum. That works but makes the view hard to use, so alias every expression.
You can also name the columns in a list after the view name. The list replaces the query's names by position:
CREATE MATERIALIZED VIEW sales_monthly (month, order_count, revenue) AS
SELECT date_trunc('month', order_date)::date,
count(*),
sum(total)
FROM orders
GROUP BY 1;The query's columns are matched to the list in order, so the list must not name more columns than the query returns. Fewer names are allowed. Any extra query columns keep their own names, so a short list is an easy way to rename only the leading columns by accident. In practice, either alias in the query or list every column, and don't mix the two.
Two columns with the same name cause an error, so aliases also help with joins that return id from two tables.
CREATE MATERIALIZED VIEW order_details AS
SELECT o.id AS order_id,
o.order_date,
o.customer_id,
o.total
FROM orders o
WHERE o.total > 100;Using IF NOT EXISTS
A script that creates a materialized view fails on its second run, because the name is already taken. IF NOT EXISTS makes the statement idempotent:
CREATE MATERIALIZED VIEW IF NOT EXISTS sales_daily AS
SELECT order_date AS day,
count(*) AS orders,
sum(total) AS revenue
FROM orders
GROUP BY order_date;If sales_daily exists, PostgreSQL prints a notice and does nothing.
The name check covers all relations in the schema, so a table, plain view, sequence, or index with that name also blocks the statement. All of these share one namespace per schema.
Rules the query must follow
The defining query is mostly ordinary SELECT, with these constraints:
- It can use joins, aggregates, window functions, CTEs, subqueries, and set operations.
- It cannot reference temporary tables or temporary views. PostgreSQL rejects the statement because a permanent object would depend on a session-local one.
- It cannot take parameters. The query is fixed text, so there is no equivalent of a function argument. If you need per-customer slices, filter the view when you read it.
- It cannot contain data-modifying statements such as
INSERT ... RETURNINGinside a CTE. - Functions in the query that depend on the session, such as
CURRENT_DATEornow(), are evaluated when the query runs, and the result is stored. A view that filters onCURRENT_DATEkeeps showing the date it was last populated.
That last point surprises many people:
CREATE MATERIALIZED VIEW todays_orders AS
SELECT * FROM orders WHERE order_date = CURRENT_DATE;Tomorrow this view still holds today's rows. It becomes correct again only when you refresh it. For this reason, rolling-window views are a common source of staleness bugs.
Ordering
You may write ORDER BY in the defining query, and PostgreSQL stores the rows in that order at creation. Reads do not guarantee any order, though. An index scan, a parallel scan, or a later refresh can return rows differently. Always put ORDER BY on the SELECT that reads the view.
The view is read-only
You cannot change the stored rows directly.
INSERT INTO sales_daily VALUES (CURRENT_DATE, 1, 10.00);This fails with an error saying you cannot change a materialized view. The same applies to UPDATE and DELETE. The only way to change the contents is to refresh the view from its query, which later chapters cover. Unlike simple plain views, materialized views are never automatically updatable.
A snapshot, not a live query
The stored rows describe the base tables as they were when the query ran. Compare the two objects:
INSERT INTO orders (customer_id, order_date, total)
VALUES (1, CURRENT_DATE, 25.00);
SELECT count(*) FROM orders;
SELECT sum(orders) FROM sales_daily;The first count includes the new row and the second sum does not. Nothing in PostgreSQL pushes the change into the view. Bringing the view up to date is the job of REFRESH MATERIALIZED VIEW, covered in the next chapter.
Skipping the initial load
By default the query runs at creation time (WITH DATA). Adding WITH NO DATA stores the definition but skips the query:
CREATE MATERIALIZED VIEW customer_totals AS
SELECT customer_id, sum(total) AS lifetime_value
FROM orders
GROUP BY customer_id
WITH NO DATA;The view exists but is unpopulated, and selecting from it raises an error until the first refresh. A later chapter covers this state and how to check it. For now, know that it is useful in deployment scripts, where you want to create all objects quickly and load data afterward.
Storage options and ownership
Materialized views have a physical presence, so some table settings apply to them.
- Access method.
USING heapis the default and the right choice almost always. Other methods exist only if an extension installs them. - Tablespace.
TABLESPACEis useful when large views should sit on different storage than the rest of the database. - Storage parameters.
WITH (fillfactor = 100)and similar options tune page layout. Because the view is rewritten wholesale on refresh rather than updated row by row, you rarely need to change them.
The user who runs the statement becomes the owner. Reading the view requires SELECT privilege on the view itself. The base-table privileges that matter are the owner's, because the owner's rights are used when the query runs, including during later refreshes. A user who can read sales_daily does not need any access to orders. This makes a materialized view a convenient way to expose aggregates without exposing the rows behind them.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `relation "sales_daily" already exists` | The name is taken by a table, view, or index in the schema. | Choose another name, or use `IF NOT EXISTS` if reuse is intended. |
| `column "x" specified more than once` | Two output columns share a name. | Alias one of them in the query. |
| Error about temporary tables | The query references a temp table or temp view. | Use a permanent table, or inline the query. |
| Columns named `count` or `sum` | Expressions had no alias. | Add `AS name` to each expression. |
| Error when selecting right after creation | The view was created `WITH NO DATA`. | Run a refresh. |
| Stale `CURRENT_DATE` filter | The function was evaluated at creation time. | Refresh on a schedule, or filter at read time. |
Practical guidance
- Alias every expression in the defining query so column names are stable and readable.
- Keep the query deterministic where you can, and avoid
CURRENT_DATEornow()filters inside the definition. - Write definitions in a migration file under version control, since you must drop and recreate the view to change it.
- Create the view in the schema your application reads from, and grant
SELECTexplicitly. - Test the query on its own and look at its runtime first. The creation statement takes about as long as the query does.
Exercise
You run CREATE MATERIALIZED VIEW IF NOT EXISTS sales_daily AS SELECT ... with an updated query, and the statement reports success. Why might sales_daily still return results from the old query, and how do you apply the new definition?
Show answer
IF NOT EXISTS only checks that a relation with that name exists. Because sales_daily already existed, PostgreSQL printed a notice and skipped the statement without running the new query or replacing the definition. To apply the new query, drop the view with DROP MATERIALIZED VIEW sales_daily; and run CREATE MATERIALIZED VIEW sales_daily AS ... again with the new query.
Exercise
A view is defined as SELECT * FROM orders WHERE order_date = CURRENT_DATE and created on Monday. On Wednesday, a user selects from it. What do they see, and why?
Show answer
They see Monday's orders. CURRENT_DATE was evaluated when the query ran at creation, and the result rows were stored. Reads return the stored rows and do not re-run the query, so the view shows Wednesday's data only after a refresh.
Exercise
Write a statement that creates a materialized view big_orders with the columns order_id and amount, containing the id and total of orders over 150, using a column list rather than aliases in the query. Then say what happens if you run DELETE FROM big_orders.
Show answer
CREATE MATERIALIZED VIEW big_orders (order_id, amount) AS SELECT id, total FROM orders WHERE total > 150; The DELETE fails with an error that you cannot change a materialized view. Its contents can change only through a refresh.