views and materialized views
named queries, updatable views, and a cached result you refresh yourself.
- address
- everything.design.views
- part
- part 7, schema design
- chapter
- chapter 12 of 13
- reading time
- 8 min
a view is a named query. it stores no rows: when you select from it, postgres pastes its definition into your query (the rewriter), and the planner optimizes the whole thing as if you'd typed it. simple views are updatable, and WITH CHECK OPTION stops writes that would fall outside the view.
a view runs with its owner's rights unless it's security_invoker (postgres 15). a materialized view does store rows: a snapshot of the query, stale until you REFRESH it, and REFRESH ... CONCURRENTLY needs a unique index.
the picture
you know the query everyone copies from the wiki, with the four joins and the "WHERE NOT deleted"? a view gives it a name, so there's one copy, and changing the definition changes it for everyone.
think of a saved search in your email (a view): it holds no emails, it re-runs every time you click it, so it's always current. a materialized view is a printout of the search results: instant to read, and wrong the moment a new email arrives, until you print it again.
CREATE VIEW order_summary AS
SELECT o.id, o.status, o.ordered_at, c.name AS customer, c.city
FROM orders AS o
LEFT JOIN customers AS c ON c.id = o.customer_id;
SELECT id, status, customer FROM order_summary WHERE id = 5;| idint4 | statustext | customertext |
|---|---|---|
| 5 | delivered | Amelia Sato |
SELECT id, status FROM order_summary WHERE id = 5. the view is gone: its definition was pasted in, the WHERE moved down to an index scan on orders, and the LEFT JOIN to customers was removed entirely, because no customer column is used and customers.id is unique.SELECT id, status FROM order_summary WHERE id = 5;
EXPLAIN (FORMAT JSON) SELECT id, status FROM order_summary WHERE id = 5;| idint4 | statustext |
|---|---|
| 5 | delivered |
that's the whole performance story of plain views: there isn't one. a view costs what its expanded query costs, no more (the planner can push filters into it and drop unused joins) and no less (nothing is cached). the rewriting step is in the life of a query; the stored definition is a rule in pg_rewrite, and pg_get_viewdef('order_summary') prints it back.
two things a view pins down: its column list is fixed when it's created (SELECT * in a view expands to the columns that existed then), and you can't drop or retype a column a view depends on without dropping the view first.
writing through a view
a view over one table, with no aggregates, DISTINCT, GROUP BY, set operations or window functions, is automatically updatable: INSERT, UPDATE and DELETE on it become writes on the base table. that's how a view can be an API: the app sees cheap, and the table can change underneath.
the surprise is that the view's WHERE doesn't limit what you write:
- 1INSERT INTO cheap VALUES (4, 'tea chest', 30.00);
- 2SELECT id, name, price FROM cheap ORDER BY id;
| idint4 | nametext | pricenumeric |
|---|---|---|
| 1 | assam tea | 6.50 |
the row went into products, and the view can't see what it just inserted.
WITH CHECK OPTION is CASCADED by default: the row must also satisfy the conditions of any view this one is built on. LOCAL checks only this view's own WHERE. for views that aren't automatically updatable (a join, an aggregate), an INSTEAD OF trigger can define what a write means.
CREATE VIEW cheap AS
SELECT id, name, price FROM products WHERE price < 10;
INSERT INTO cheap VALUES (4, 'tea chest', 30.00);whose rights does a view use?
by default, a view accesses its tables with the rights of the view's owner. that's a feature: grant a role SELECT on a view that shows some columns, and it can read those columns without any right on the table. security_invoker = true pg 15+ flips it: the tables are checked against the user running the query.
- 1SET ROLE views_clerk;
- 2SELECT name, price FROM price_list ORDER BY name;
| nametext | pricenumeric |
|---|---|
| assam tea | 6.50 |
| blue mug | 12.00 |
| tea chest | 30.00 |
| teapot | 45.00 |
as the clerk, the default view: it reads products with its owner's rights, so it works.
the default is also a trap with row-level security: RLS policies on the base table are checked against the view owner, often the table's owner, who bypasses them. a security_invoker view applies the caller's policies, which is usually what you meant.
materialized views
CREATE MATERIALIZED VIEW runs the query once and stores the rows in a real table. reading it is reading that table, indexes and all. nothing keeps it current:
- 1INSERT INTO order_lines VALUES (102, 3, 3);
- 2SELECT id, name, revenue FROM revenue ORDER BY id;
| idint4 | nametext | revenuenumeric |
|---|---|---|
| 1 | assam tea | 32.50 |
| 2 | blue mug | 12.00 |
the materialized view still shows what was true when it was built. no teapot.
plain REFRESH MATERIALIZED VIEW recomputes the whole thing and swaps it in under an ACCESS EXCLUSIVE lock: readers wait until it's done. CONCURRENTLY computes the new result on the side, diffs it against the old one, and applies the difference with ordinary inserts, updates and deletes, so readers keep reading. to match old rows to new ones it needs a unique index on plain columns (no WHERE clause) covering all rows. it's slower than a plain refresh, and two refreshes of one view can't run at once.
when to reach for one: a dashboard or report over a big aggregate that can be minutes old, refreshed by a scheduler (pg_cron, or the app). when not to: anything that has to be right at commit, where a trigger-kept summary is the tool. postgres has no incremental refresh built in; every refresh reruns the whole query.
keylines
- a view is a named query, pasted into yours by the rewriter; it stores nothing and costs what it expands to.
- simple views are updatable, and their WHERE doesn't limit writes without WITH CHECK OPTION.
- views run with the owner's rights; security_invoker (15+) uses the caller's.
- a materialized view is a stored snapshot, stale until REFRESH.
- REFRESH ... CONCURRENTLY keeps readers going, and needs a unique index.