Sub topic 4
Adding indexes to speed up reads
Assume sales_daily is an existing PostgreSQL materialized view with these columns:
day: the date being summarizedorders: the number of ordersrevenue: the total sales amount
This chapter assumes that you know CREATE INDEX, basic query filters, and how to read a simple EXPLAIN plan.
Why index a materialized view?
A materialized view stores query results as rows. PostgreSQL can therefore build indexes on it just as it can on a table.
Without an index, PostgreSQL may scan every row in the materialized view to answer a query. An index gives PostgreSQL another access path. It can find matching rows or read rows in a useful order without scanning the entire relation.
For example, this query often looks for one day:
SELECT day, orders, revenue
FROM sales_daily
WHERE day >= CURRENT_DATE - 30
ORDER BY day DESC;An index on day can help with both the date condition and the ordering:
CREATE INDEX sales_daily_day_idx
ON sales_daily (day);The index does not change the rows stored in the materialized view. It only changes how PostgreSQL can locate those rows.
Choose indexes for real queries
Create indexes for the access patterns your application actually uses. An index has storage and maintenance costs, so adding one for every column usually makes the system slower to refresh and harder to maintain.
Common choices include:
| Query pattern | Possible index |
|---|---|
| Filter by `day` | `ON sales_daily (day)` |
| Filter by customer, then date | `ON customer_totals (customer_id, day)` |
| Sort by date descending | `ON sales_daily (day DESC)` |
| Look up a unique summary row | `UNIQUE ON customer_totals (customer_id)` |
Column order matters for a multicolumn index. An index on (customer_id, day) is most useful when a query restricts customer_id. It can then narrow the search by day. It is usually less useful for a query that filters only by day.
PostgreSQL can also use an index for joins. Suppose a materialized view stores one row per customer:
CREATE INDEX customer_totals_customer_idx
ON customer_totals (customer_id);
SELECT c.name, t.lifetime_value
FROM customers AS c
JOIN customer_totals AS t
ON t.customer_id = c.id
WHERE c.id = 42;The index can make the lookup into customer_totals fast.
Inspect whether PostgreSQL uses the index
Use EXPLAIN to inspect the plan chosen for a query:
EXPLAIN
SELECT day, orders, revenue
FROM sales_daily
WHERE day >= CURRENT_DATE - 30
ORDER BY day DESC;For actual execution statistics, use EXPLAIN (ANALYZE, BUFFERS). This runs the query, so use it carefully for expensive statements:
EXPLAIN (ANALYZE, BUFFERS)
SELECT day, orders, revenue
FROM sales_daily
WHERE day >= CURRENT_DATE - 30
ORDER BY day DESC;A plan containing Index Scan or Index Only Scan shows that PostgreSQL used an index. A Seq Scan is not automatically a problem. If the materialized view is small or the query returns most rows, scanning the relation can be cheaper than using the index.
Indexes and refreshes
A normal refresh updates the stored contents and keeps the materialized view's indexes available:
REFRESH MATERIALIZED VIEW sales_daily;The refresh still has work to do because the index structures must match the refreshed rows. More indexes can therefore increase refresh time and temporary resource use.
This creates a trade-off:
- More indexes can make dashboard and lookup queries faster.
- Fewer indexes can make refreshes faster and use less storage.
- An index that supports no important query adds cost without a benefit.
Measure both read performance and refresh duration before adding several indexes.
Indexing for concurrent refresh
REFRESH MATERIALIZED VIEW CONCURRENTLY requires at least one unique index that covers all rows and uses only plain column names. It cannot be a partial index or an expression index.
For a view with exactly one row per day, this index satisfies the requirement:
CREATE UNIQUE INDEX sales_daily_day_unique_idx
ON sales_daily (day);
REFRESH MATERIALIZED VIEW CONCURRENTLY sales_daily;The day values must actually be unique. If duplicate rows can exist, PostgreSQL cannot use this index. Create a unique index only when the materialized view's result guarantees uniqueness.
Practical checklist
Before creating an index, ask:
- Which
WHERE,JOIN, orORDER BYclause needs faster access? - Is the indexed column, or column combination, selective enough?
- Does column order match the most common predicates?
- Will the index satisfy the unique-index requirement for concurrent refresh?
- How much time and storage will the index add to refreshes?
Exercise
Why might PostgreSQL choose a sequential scan even when an index exists on the filtered column?
Show answer
A sequential scan may be cheaper when the materialized view is small or the query returns a large portion of its rows.