Sub topic 1
Views, materialized views, and tables: what is stored and what is not
PostgreSQL gives you three ways to put a name on a set of rows: a table, a view, and a materialized view. They look the same in a SELECT, but they differ in what the database keeps on disk and when the rows are computed. This chapter builds a working model of that difference. Later chapters cover creating, indexing, and refreshing materialized views in detail.
Prerequisites
This chapter assumes you already have:
- Basic SQL:
SELECT,JOIN,GROUP BY, and aggregate functions such ascountandsum. - Some familiarity with tables and plain views, including
CREATE VIEW. - A basic idea of what an index does.
- Access to a PostgreSQL server (version 12 or later is fine) and
psqlor another SQL client where you can run the examples.
The core question: what is stored?
Each of the three objects answers two questions differently. The first is whether the rows are physically stored. The second is when the query that produces the rows runs.
- A table stores its rows. Nothing is computed. You write rows with
INSERT,UPDATE, andDELETE. - A view stores only a query. Each time you select from the view, PostgreSQL runs that query against the underlying tables.
- A materialized view stores a query and also its result rows. The query runs when you create the view and again each time you refresh it. In between, a
SELECTreads the stored rows.
A materialized view is like a table whose contents are produced by a query. You do not edit it directly. You ask PostgreSQL to rebuild it.
A worked comparison
The following script creates one base table, then a plain view and a materialized view with the same aggregate query. Run it in a scratch database.
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, CURRENT_DATE - 1, 40.00),
(2, CURRENT_DATE - 1, 15.50),
(1, CURRENT_DATE, 25.00);
CREATE VIEW sales_daily_v AS
SELECT order_date AS day,
count(*) AS orders,
sum(total) AS revenue
FROM orders
GROUP BY order_date;
CREATE MATERIALIZED VIEW sales_daily_m AS
SELECT order_date AS day,
count(*) AS orders,
sum(total) AS revenue
FROM orders
GROUP BY order_date;Both objects return the same two rows right now:
SELECT * FROM sales_daily_v ORDER BY day;
SELECT * FROM sales_daily_m ORDER BY day;Now add an order and query both again:
INSERT INTO orders (customer_id, order_date, total)
VALUES (3, CURRENT_DATE, 60.00);
SELECT * FROM sales_daily_v WHERE day = CURRENT_DATE;
SELECT * FROM sales_daily_m WHERE day = CURRENT_DATE;The plain view reports 2 orders and 85.00 in revenue for today. The materialized view still reports 1 order and 25.00, because it holds the rows computed when it was created. That gap is called staleness. It is the defining trade-off of a materialized view, and a later chapter returns to it.
Looking at what PostgreSQL actually keeps
The system catalog confirms the model. The pg_class catalog lists every relation, and its relkind column tells you the kind: r for an ordinary table, v for a view, and m for a materialized view.
SELECT relname,
relkind,
pg_relation_size(oid) AS bytes_on_disk
FROM pg_class
WHERE relname IN ('orders', 'sales_daily_v', 'sales_daily_m')
ORDER BY relname;Expect these results:
| relname | relkind | bytes_on_disk |
|---|---|---|
| orders | r | 8192 (one page, for this small table) |
| sales_daily_m | m | 8192 (one page of stored result rows) |
| sales_daily_v | v | 0 |
The plain view occupies no storage. Its definition is stored as a rewrite rule, which you can read back with pg_get_viewdef:
SELECT pg_get_viewdef('sales_daily_v'::regclass, true);The materialized view has a heap file like a table, so it can also have indexes. That is its main advantage over a plain view.
Writing to each kind
You can write to tables freely. A view's writability depends on its definition. PostgreSQL supports automatically updatable views for simple cases, but the aggregate view above is not one of them. A materialized view cannot be written to by any INSERT, UPDATE, or DELETE:
INSERT INTO sales_daily_m (day, orders, revenue)
VALUES (CURRENT_DATE, 1, 1.00);PostgreSQL rejects this with cannot change materialized view "sales_daily_m". The only supported way to change its rows is to re-run the saved query, which is a refresh.
Side-by-side summary
| Property | Table | View | Materialized view |
|---|---|---|---|
| Stores rows on disk | Yes | No | Yes |
| Stores the query | No | Yes | Yes |
| When the query runs | Never | Every `SELECT` | At creation and at each refresh |
| Reflects base-table changes | Not applicable | Immediately | Only after a refresh |
| Can have indexes | Yes | No | Yes |
| Direct `INSERT`/`UPDATE`/`DELETE` | Yes | Only if simple enough | No |
| `relkind` in `pg_class` | `r` | `v` | `m` |
Why not just use a table?
You could copy the query result into a table yourself with CREATE TABLE ... AS SELECT. That produces stored rows, but PostgreSQL forgets how they were made. You would have to keep the query in a script and rebuild the table by hand, perhaps with TRUNCATE and INSERT ... SELECT.
A materialized view keeps the defining query inside the database. That brings three benefits:
REFRESH MATERIALIZED VIEWneeds no copy of the query.- Tools and teammates can find the definition in the catalog.
- PostgreSQL tracks dependencies, so it will not let you drop a base table that the view still depends on unless you use
CASCADE.
The cost is rigidity. You cannot patch single rows, and you cannot change the query without dropping and recreating the view (a later chapter covers altering and dropping).
Security and ownership differences
Because a materialized view stores results, access works differently from a plain view.
- When you select from a plain view, PostgreSQL checks permissions on the underlying tables as the view's owner, not as the caller (unless the view was created with
security_invokeron PostgreSQL 15 or later). GrantingSELECTon the view is enough for callers. - A materialized view's query runs with the owner's privileges at creation and at refresh time. Readers need
SELECTon the materialized view only.
Row-level security policies on the base table were applied when the owner refreshed the view. They are not applied again per reader. If you use row-level security, check that your materialized view does not expose rows that its readers should not see.
Common errors and misconceptions
- "My materialized view is wrong." Usually it is just stale. Compare it with the plain query before assuming a bug.
- Assuming it updates automatically. PostgreSQL has no built-in incremental maintenance of materialized views and does not refresh them on commit.
- Treating it as a free cache. The stored result takes disk space. Rebuilding it costs as much as running the full query, and for a large aggregate that can be minutes.
- Trying to
INSERTinto it. This fails with the error shown earlier. Change the base tables and refresh. - Expecting a plain view to be fast. A view adds no speed. It runs the same query each time, so an expensive aggregate stays expensive.
- Dropping the wrong object.
DROP VIEWdoes not work on a materialized view. UseDROP MATERIALIZED VIEW. Mixing them up gives an error that names the correct command.
A quick decision frame
Before reaching for a materialized view, ask three questions. The decision chapter at the end of this tutorial covers them in full.
- Is the underlying query slow enough to matter, for example a large aggregate or a join across big tables?
- Is it acceptable for readers to see data that is minutes or hours old?
- Is the query read far more often than the base data changes?
If you answer no to the first, a plain view is simpler. If you answer no to the second, a plain view or a query-time approach is safer. If you answer no to the third, you may spend more time refreshing than you save.
Exercise
You create a plain view v and a materialized view m over the same query on table t. Then you insert a new row into t and do not run any other command. Which of v and m includes the new row, and how can you tell from pg_class that one of them stores nothing on disk?
Show answer
The plain view v includes the new row, because its saved query runs against t on every SELECT. The materialized view m does not include it until a refresh, because it returns the rows stored at creation or last refresh. In pg_class, v has relkind = 'v' and pg_relation_size('v') returns 0, while m has relkind = 'm' and a nonzero size.
Exercise
A teammate runs UPDATE sales_daily_m SET revenue = 0 WHERE day = CURRENT_DATE; to fix a number in a materialized view. What happens, and what is the correct way to change what the view shows?
Show answer
The statement fails with an error saying you cannot change a materialized view. To change what it shows, fix the data in the base table (here orders) and run REFRESH MATERIALIZED VIEW sales_daily_m, which re-runs the defining query and replaces the stored rows.