skip to content

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.

order_summary.sqldb=shop · session v
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;
output, from postgres 18.6
#1 · CREATE VIEW
#2 · SELECT 1
idint4statustextcustomertext
5deliveredAmelia Sato
(1 row)
show =
estimated rows
the plan for 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.
sqldb=shop · session v
continues session v (1 earlier block run first)
SELECT id, status FROM order_summary WHERE id = 5;
 
EXPLAIN (FORMAT JSON) SELECT id, status FROM order_summary WHERE id = 5;
output, from postgres 18.6
#1 · SELECT 1
idint4statustext
5delivered
(1 row)
#2 · EXPLAIN
[ { "Plan": { "Node Type": "Index Scan", "Parallel Aware": false, "Async Capable": false, "Scan Direction": "Forward", "Index Name": "orders_pkey", "Relation Name": "orders", "Alias": "o", "Startup Cost": 0.29, "Total Cost": 8.3, "Plan Rows": 1, "Plan Width": 13, "Disabled": false, "Index Cond": "(id = 5)" } } ]

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:

view =
cheap.sql
  1. 1INSERT INTO cheap VALUES (4, 'tea chest', 30.00);
  2. 2SELECT id, name, price FROM cheap ORDER BY id;
the result for plain view
idint4nametextpricenumeric
1assam tea6.50
(1 row)

the row went into products, and the view can't see what it just inserted.

real output, postgres 18.6 (PGlite 0.5.12) · views
a view of products under 10.00. insert a 30.00 product through the plain view: it goes into products, and the view can't see the row it just inserted. WITH CHECK OPTION refuses any insert or update whose result the view wouldn't show, with SQLSTATE 44000.

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.

predict the output
sql
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.

security_invoker =
price_list.sql
  1. 1SET ROLE views_clerk;
  2. 2SELECT name, price FROM price_list ORDER BY name;
the result for false (the default)
nametextpricenumeric
assam tea6.50
blue mug12.00
tea chest30.00
teapot45.00
(4 rows)

as the clerk, the default view: it reads products with its owner's rights, so it works.

real output, postgres 18.6 (PGlite 0.5.12) · views
a clerk role with SELECT on two views of products, and no right on products itself. the default view reads products as its owner, so it works. the security_invoker view checks the clerk, and fails. real, with SET ROLE in this page's engine.

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:

read =
revenue.sql
  1. 1INSERT INTO order_lines VALUES (102, 3, 3);
  2. 2SELECT id, name, revenue FROM revenue ORDER BY id;
the result for the materialized view
idint4nametextrevenuenumeric
1assam tea32.50
2blue mug12.00
(2 rows)

the materialized view still shows what was true when it was built. no teapot.

real output, postgres 18.6 (PGlite 0.5.12) · views
revenue per product, as a materialized view, after three teapots were ordered. the materialized view is stale: no teapot. the live query sees it. REFRESH ... CONCURRENTLY fails without a unique index, and works with one.

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.