{"canonical_url":"https://engineer.company/glossary/materialized-view/","content_markdown":"# Materialized view\n\n## What it is\n\nA materialized view is a query whose result the database keeps, so that reading\nit returns rows computed earlier instead of running the query again. In British\nspelling it is a materialised view. It sits between two older objects. A plain\nview stores only its query, and every read runs that query against the tables\nunderneath. A table created with `CREATE TABLE AS` stores a result but forgets\nthe query that produced it. A materialized view keeps both: the rows, which\nreads come from, and the query, which can be run again to replace them.\n\nPostgreSQL added materialized views in version 9.3, released on September 9,\n2013, and its release notes credit the work to Kevin Grittner. The documentation\ndescribes them as using the rule system the way ordinary views do while\npersisting the result in a table-like form. To the query parser a materialized\nview is a relation like any table or view, so a `SELECT` against it reads the\nstored rows directly; the stored query matters only when the view is filled. The\nview cannot be updated directly. To replace its contents with a fresh query\nresult, the stored query must run again.\n\nTwo commands do that work. `CREATE MATERIALIZED VIEW` defines the view and,\nunless it is told `WITH NO DATA`, runs the query at once to fill it.\n`REFRESH MATERIALIZED VIEW` runs the stored query again and replaces the whole\ncontent with the new result. Version 9.4, released on December 18, 2014, added\n`CONCURRENTLY`, which lets a refresh run without blocking the sessions that read\nthe view. Both commands are PostgreSQL extensions, not part of the SQL standard;\nother databases offer the idea under their own syntax and rules.\n\n## Why it matters\n\nSome queries are expensive and asked often: a dashboard that sums a year of\norders by day, a report that joins six tables, a page that ranks products by\nsales. Run against the source tables, every request pays for the full scan, join\nand aggregation again, although the answer barely moves between requests. A\nmaterialized view pays that cost once per refresh, and every read after that is\na scan of a small table computed in advance. PostgreSQL's documentation says\nreading the stored data is \"often much faster than accessing the underlying\ntables directly or through a view\".\n\nThe price is freshness. Between refreshes the view shows the data as it stood at\nthe last one, and in PostgreSQL nothing refreshes it unless someone, or\nsomething scheduled, asks. Many uses can live with that. Yesterday's sales do\nnot change today, and a monthly report has no need for this minute's orders.\nWhat the materialized view forces is an explicit decision: how old the answer\nmay be, and whose job it is to keep it from getting older.\n\nIt also gives indexes a place to live: the stored result can carry indexes of\nits own, built for the queries that read it. The PostgreSQL documentation shows\na second use for that: data brought in from another system through a foreign\ndata wrapper, which may not support indexes at all, can be copied into a\nmaterialized view that does.\n\nFor a team that keeps its schema normalized, this is often where the flattened\nshape belongs. Database normalization stores each fact once and answers most\nquestions through joins. A materialized view can hold the joined, summed result\nthat reporting wants, while the source tables keep their single copy of each\nfact and every write still goes to one place.\n\n## What it looks like in practice\n\nTake a shop's order tables: `orders`, with one row per order and the date it was\nplaced, and `order_lines`, with the SKU, quantity and unit price of each line. A\nsales dashboard wants units and revenue per product per day. The query is short,\nbut over several years of orders it reads every line:\n\n```sql\nCREATE MATERIALIZED VIEW daily_sales AS\nSELECT o.ordered_on                   AS day,\n       l.sku,\n       sum(l.quantity)                AS units,\n       sum(l.quantity * l.unit_price) AS revenue\nFROM   orders o\nJOIN   order_lines l USING (order_id)\nWHERE  o.ordered_on \u003c CURRENT_DATE\nGROUP  BY o.ordered_on, l.sku;\n```\n\nThe `WHERE` clause leaves out today, whose numbers are still moving, so the\ndashboard shows complete days only; the example in PostgreSQL's own\ndocumentation treats a day of unfinished sales the same way. The command runs\nthe query once and stores the result. Next comes an index:\n\n```sql\nCREATE UNIQUE INDEX daily_sales_sku_day ON daily_sales (sku, day);\n```\n\nThe index does two jobs. It lets the dashboard find one product's days without\nreading the whole view, and it is what makes a concurrent refresh possible\nlater. The query groups by day and SKU, so each pair appears once and the index\ncan be unique. From now on the dashboard reads the view like a table:\n\n```sql\nSELECT day, units, revenue\nFROM   daily_sales\nWHERE  sku = 'TEA-250'\nORDER  BY day;\n```\n\nEvery night, shortly after midnight, a scheduled job brings it up to date:\n\n```sql\nREFRESH MATERIALIZED VIEW CONCURRENTLY daily_sales;\n```\n\nWithout `CONCURRENTLY`, a refresh that touches many rows tends to use fewer\nresources and finish sooner, but it could block the dashboard's reads until it\nis done. With it, reads carry on during the refresh, and the documentation notes\nit may even be the faster choice when only a few rows change, as here, where one\nnew day arrives each night. The option has two conditions. The view must already\nhold data, and it must have at least one unique index built from plain column\nnames that covers every row, so no expression index and no `WHERE` clause. The\nindex above meets the second; creating the view with its data met the first.\n\nOther databases draw the line in other places. In BigQuery, materialized views\nare maintained in the background: changes to the base tables are added\nincrementally without anyone asking, a query against the view merges in recent\nchanges so the result stays fresh, and smart tuning can reroute a query written\nagainst the base tables to the view instead. That holds for incremental views,\nwhich accept a limited set of SQL. A view defined with\n`allow_non_incremental_definition = true` accepts most queries, but every\nrefresh runs the full query and its results are not always fresh.\n\nSQL Server reaches a similar result through indexed views. Adding a clustered\nindex that enforces uniqueness to a view, which must be created\n`WITH SCHEMABINDING` and have a deterministic definition, stores its result\nusing the same storage arrangement as an indexed table, and the optimizer can\nuse it even for a query that does not name the view. SQL Server updates the\nindexed view along with every insert, update and delete on the tables it depends\non, so there is no refresh to schedule; the cost moves to the writes, and\nMicrosoft's documentation warns that their performance can degrade\nsignificantly.\n\nThe same trade-off shows up in production work. In an earlier role, the founder\nbuilt [PL/pgSQL ETL and ELT pipelines](/portfolio/engineered-600-pl-pgsql-etl-elt-pipelines/) that used\npartitioned tables and materialized views to speed up reads on large\ndatasets, alongside primary and foreign key constraints for referential\nintegrity and unique and composite indexes for the joins.\n\n## Where it goes wrong\n\n**Stale numbers that look current.** A refresh job that stopped running a week\nago leaves the view answering every query, quickly and wrongly, and nothing in\nthe result says how old it is. Have the job record the time of each successful\nrefresh somewhere the dashboard can show it, and alert when that time is older\nthan the readers agreed to accept.\n\n**A refresh that blocks the readers.** A plain `REFRESH MATERIALIZED VIEW` over\na large view could block every session trying to read it until the refresh\nfinishes. Add a unique index and use `CONCURRENTLY`, or schedule plain refreshes\nfor hours when nobody reads the view. When most rows change on every run, the\nplain refresh may still be the cheaper one.\n\n**`CONCURRENTLY` refused.** The option needs a unique index on plain columns\ncovering all rows. A unique index on `lower(email)`, or one limited by a `WHERE`\nclause, does not qualify. It also needs a view that already holds data, so it\nfails on a view created `WITH NO DATA`, and the two options cannot be combined.\nAdd a qualifying index, and fill the view once with a plain refresh.\n\n**An unscannable view.** `WITH NO DATA` creates the view without running its\nquery and flags it unscannable, and any query against it fails until the first\nrefresh. That can be the right choice in a migration that should not wait for a\nlong query, but then the first refresh has to be planned, not forgotten.\n\n**A changed definition that never arrived.**\n`CREATE MATERIALIZED VIEW IF NOT EXISTS` in a migration does nothing, beyond a\nnotice, when a view of that name already exists, and the documentation gives no\nguarantee that the existing view resembles the new definition. A migration that\nchanges the query this way leaves the old one in place. Drop the view with\n`DROP MATERIALIZED VIEW` and create it again in the same migration.\n\n**Refresh jobs that overlap.** A materialized view can have only one refresh in\nprogress, even with `CONCURRENTLY`, so a schedule tighter than the refresh\nitself only leaves the view further behind. Measure how long a refresh takes and\nschedule from that.\n\n**Trusting the order of the rows.** If the defining query has an `ORDER BY`, the\nfirst contents come out in that order, but a refresh does not promise to keep\nit. Put the `ORDER BY` in the queries that read the view.\n\n**Functions that lose their tables.** While the defining query runs, at creation\nor on refresh, PostgreSQL temporarily sets `search_path` to\n`pg_catalog, pg_temp`, and restricts what the query may do: a function that\ncreates temporary tables fails. A function that finds its tables by unqualified\nname can pass every test by hand and break only inside the refresh.\nSchema-qualify the table names in any function the view calls.\n\n**The wrong role runs the job.** Refreshing requires the `MAINTAIN` privilege on\nthe materialized view. A job running as a reporting role that may read the view\nbut not maintain it fails every night. Give the role that runs the refresh that\nprivilege.\n\n**A stored copy where an index would do.** If a query is slow because an index\nis missing, a materialized view hides the problem and adds staleness on top.\nRead the query plan first. When a query only needs a name, a plain view is\nenough and is always current; keep materialized views for results that are\nexpensive to compute and safe to read slightly old.\n\n## Further reading\n\n- [Materialized Views](https://www.postgresql.org/docs/current/rules-materializedviews.html)\n  — PostgreSQL's chapter on how materialized views relate to views and tables,\n  with a sales summary refreshed nightly and a foreign data wrapper example.\n- [CREATE MATERIALIZED VIEW](https://www.postgresql.org/docs/current/sql-creatematerializedview.html)\n  — the command reference, including `WITH NO DATA`, `IF NOT EXISTS` and the\n  restricted `search_path` during the query.\n- [REFRESH MATERIALIZED VIEW](https://www.postgresql.org/docs/current/sql-refreshmaterializedview.html)\n  — the refresh command, the conditions for `CONCURRENTLY` and the `MAINTAIN`\n  privilege it requires.\n- [PostgreSQL 9.3 release notes](https://www.postgresql.org/docs/9.3/release-9-3.html)\n  — the release, in September 2013, that added materialized views.\n- [Introduction to materialized views](https://cloud.google.com/bigquery/docs/materialized-views-intro)\n  — BigQuery's incremental and non-incremental materialized views, automatic\n  refresh and smart tuning.\n- [Create indexed views](https://learn.microsoft.com/en-us/sql/relational-databases/views/create-indexed-views)\n  — SQL Server's indexed views, their requirements and their cost to writes.\n\n\u003chttps://engineer.company/glossary/materialized-view/\u003e\n","date_modified":"2026-11-09T21:50:25Z","description":"What a materialized view is: a stored query result in PostgreSQL, how REFRESH and CONCURRENTLY work, how BigQuery and SQL Server differ, and where it fails.","formats":{"gemtext":"https://engineer.company/glossary/materialized-view/index.gmi","gopher":"https://engineer.company/glossary/materialized-view/gophermap","html":"https://engineer.company/glossary/materialized-view/","json":"https://engineer.company/glossary/materialized-view/index.json","markdown":"https://engineer.company/glossary/materialized-view/index.md","pdf":"https://engineer.company/glossary/materialized-view/index.pdf"},"kind":"page","language":"en","title":"What is a materialized view?","url":"https://engineer.company/glossary/materialized-view/","version":1}