Sub topic 4
Adding indexes to speed up reads
This chapter assumes you can write SELECT, JOIN, and GROUP BY queries and have created a materialized view with CREATE MATERIALIZED VIEW. You should also know what a B-tree index is and how to read a basic EXPLAIN plan.
Why a materialized view needs its own indexes
A materialized view stores the rows of its query as a physical relation. It is a relation in the same sense that a table is. That has a consequence people often miss. Indexes on the base tables do not carry over to the view. The view holds its own copy of the data, so a query against it can only use indexes created on the view itself.
Without an index, every filtered read of a materialized view is a sequential scan of the whole stored result. For a small aggregate, such as a few hundred daily totals, that is fine. For a view with millions of rows, such as one row per customer per day, it is the same problem you were trying to escape.
Use this model. The view's query runs at creation and at each refresh. Indexes are rebuilt as part of that work. In between refreshes, reads use the stored rows and the indexes on them.
Creating an index
You create an index on a materialized view with the ordinary CREATE INDEX statement. The view takes the place of the table name.
CREATE TABLE orders (
id bigserial PRIMARY KEY,
customer_id integer NOT NULL,
order_date date NOT NULL,
total numeric(10,2) NOT NULL
);
CREATE MATERIALIZED VIEW sales_daily AS
SELECT order_date AS day,
count(*) AS orders,
sum(total) AS revenue
FROM orders
GROUP BY order_date;
CREATE INDEX sales_daily_revenue_idx ON sales_daily (revenue);The index is on the view's output column revenue, not on anything in orders. Column names come from the view's column list, which is why the alias day is used in the index definition and not order_date.
You can use the same index features you use on tables:
- Multicolumn indexes, for filters that combine columns.
- Partial indexes, with a
WHEREclause. - Expression indexes, such as
lower(email). - Index types other than B-tree, such as GIN or BRIN, when the column's data type calls for them.
Here is a partial index that serves a "best days" report without indexing every row:
CREATE INDEX sales_daily_big_days_idx
ON sales_daily (day DESC)
WHERE revenue > 10000;Which columns to index
Index the columns that your queries filter, join, or sort on. Do not index by default. Each index costs disk space and time at every refresh.
Think about the access patterns of the view as you would for a table:
| Query pattern | Useful index |
|---|---|
| `WHERE day = DATE '2026-11-01'` | B-tree on `day` |
| `WHERE day BETWEEN a AND b ORDER BY day` | B-tree on `day`, which serves the range and the order |
| `WHERE customer_id = 42 AND day >= a` | Multicolumn B-tree on `(customer_id, day)` |
| Filter on a tiny, hot subset | Partial index |
| Very large view, values correlate with physical order | BRIN |
Column order in a multicolumn index matters. Put equality-filtered columns first and range-filtered columns after them.
Seeing the index work
Check that the planner uses your index with EXPLAIN. Small views may still get a sequential scan, because reading a few pages is cheaper than traversing an index. That is correct planner behavior and not a fault in your index.
CREATE INDEX sales_daily_day_idx ON sales_daily (day);
EXPLAIN
SELECT * FROM sales_daily WHERE day = DATE '2026-11-01';On a view with enough rows you should see an Index Scan or Bitmap Heap Scan on sales_daily_day_idx. If you still see Seq Scan on a large view, run ANALYZE sales_daily; so the planner has current statistics, then check again.
ANALYZE sales_daily;Statistics matter here. A refresh replaces the contents of the view, but you should not assume it also leaves statistics fresh for the new data. Autovacuum's analyze step does run on materialized views, but only after enough rows change and on its own timing. After a very large refresh, run ANALYZE yourself if the plans look wrong.
What happens to indexes during a refresh
The two refresh forms treat indexes differently.
A plain REFRESH MATERIALIZED VIEW runs the query and replaces the stored contents. Indexes on the view are rebuilt as part of this replacement. The command takes an ACCESS EXCLUSIVE lock on the view, so readers wait until it finishes. Because the whole relation is rewritten, you do not accumulate dead index entries across refreshes.
REFRESH MATERIALIZED VIEW CONCURRENTLY works differently. It builds the new result in a temporary area, compares it with the current contents, and applies only the differences with inserts and deletes. Readers are not blocked during that time. Because it changes rows in place, it behaves like ordinary DML on the view. The existing indexes are updated incrementally, and dead tuples build up that vacuum must later clean.
The key point for this chapter: the concurrent form has a hard requirement on indexes. The view must have at least one unique index that:
- Uses only plain column names (no expressions).
- Is not a partial index (no
WHEREclause). - Covers all rows of the view.
PostgreSQL uses that index to match old rows to new rows during the comparison.
CREATE UNIQUE INDEX sales_daily_day_uidx ON sales_daily (day);
REFRESH MATERIALIZED VIEW CONCURRENTLY sales_daily;The unique index is valid here because sales_daily is grouped by order_date, so each day appears exactly once.
Choosing a unique index
When the view's query has a natural key, use it. In sales_daily, the grouping column is the key. For a view grouped by several columns, the unique index must list all of them:
CREATE MATERIALIZED VIEW sales_by_customer_day AS
SELECT customer_id,
order_date AS day,
sum(total) AS revenue
FROM orders
GROUP BY customer_id, order_date;
CREATE UNIQUE INDEX sales_by_customer_day_uidx
ON sales_by_customer_day (customer_id, day);If the view has no natural key, such as a plain join that can repeat rows, you have two options. You can add a key to the query, for example by selecting orders.id. Or you can accept that CONCURRENTLY is not available for that view. Do not add a unique index that the data can violate. A refresh would fail with a unique violation, and a unique index also rejects duplicate rows when the view is first populated.
Be careful with NULL. A unique index treats NULL values as distinct from each other by default. If a key column can hold NULL, two rows with NULL do not conflict, but the concurrent refresh cannot match them to each other either. Keep key columns NOT NULL in the source query where you can.
Common errors
These are the failures you are most likely to see.
Error: cannot refresh materialized view concurrently. The message tells you to create a unique index with no WHERE clause on one or more columns. You have no qualifying unique index, or the only unique index is partial or built on an expression. Create a full unique index on plain columns.
Error: materialized view has not been populated. This happens with a view created WITH NO DATA. A concurrent refresh cannot be the first one. Run a plain REFRESH MATERIALIZED VIEW first. A later chapter covers unpopulated views in detail.
A query is still slow after you added an index. Check, in order:
- Does the query's filter match the index columns and their order?
- Did you run
ANALYZEafter the last big refresh? - Does
EXPLAINshow the index at all, or is the view small enough that a sequential scan wins?
Refreshes became slower after adding many indexes. Every index must be rebuilt (plain refresh) or maintained (concurrent refresh). Drop indexes that no query uses. You can find candidates in pg_stat_user_indexes by looking for rows with idx_scan = 0.
SELECT indexrelname, idx_scan
FROM pg_stat_user_indexes
WHERE relname = 'sales_daily'
ORDER BY idx_scan;Indexes and view definition changes
Indexes live on the stored relation, not on the query. If you need to change the view's query, you must drop and recreate the view. CREATE OR REPLACE MATERIALIZED VIEW does not exist. Dropping the view drops its indexes, so keep the index definitions in the same migration script as the view, and recreate them right after CREATE MATERIALIZED VIEW.
A useful order for a deployment script is:
- Create the view, using
WITH NO DATAif the query is expensive. - Create the indexes while the view is empty, which is fast.
- Run
REFRESH MATERIALIZED VIEWto populate it.
This order avoids building indexes over a large result after the fact. It also makes the first CONCURRENTLY refresh possible, because the unique index already exists.
Summary of the working model
- A materialized view is a stored relation, so it needs its own indexes.
- Index the columns that readers filter, join, and sort on, and verify with
EXPLAIN. - Every index adds cost to each refresh, so keep only the ones that earn it.
REFRESH ... CONCURRENTLYrequires a unique index on plain columns with noWHEREclause.- Run
ANALYZEafter large refreshes if plans look wrong.
Exercise
A view sales_by_customer_day is defined as SELECT customer_id, order_date AS day, sum(total) AS revenue FROM orders GROUP BY customer_id, order_date. Write the statement that lets you run REFRESH MATERIALIZED VIEW CONCURRENTLY on it, and explain why a unique index on customer_id alone would not work.
Show answer
CREATE UNIQUE INDEX sales_by_customer_day_uidx ON sales_by_customer_day (customer_id, day); The grouping columns are customer_id and day, so each pair appears once. A customer has one row per day, so customer_id alone repeats. Building a unique index on it would fail, and the data violates it.
Exercise
You created CREATE UNIQUE INDEX sd_idx ON sales_daily (day) WHERE revenue > 0; and then ran REFRESH MATERIALIZED VIEW CONCURRENTLY sales_daily;. What happens, and how do you fix it?
Show answer
The refresh fails because the only unique index is partial, and the concurrent form needs a unique index with no WHERE clause that covers all rows. Create CREATE UNIQUE INDEX sales_daily_day_uidx ON sales_daily (day); and refresh again. You can drop the partial index if no query needs it.
Exercise
A query SELECT * FROM sales_daily WHERE day = DATE '2026-11-01' shows a Seq Scan even though an index on day exists. Name two reasons this can be correct or fixable.
Show answer
The view may be small enough that a sequential scan is cheaper than an index lookup, so the planner choice is correct. Or the planner statistics may be stale after a large refresh, which ANALYZE sales_daily; fixes.