Sub topic 2
Adding indexes to speed up reads
This chapter assumes you know basic SQL (SELECT, GROUP BY, and aggregate functions), understand what an index is, have created a plain view and a materialized view, and can connect to PostgreSQL with psql. The examples use the sales_daily materialized view from the previous chapter.
Adding indexes to speed up reads
A materialized view stores its rows on disk, so you can create an index on it as you would on a table. An index lets PostgreSQL find matching rows without scanning the whole stored result.
CREATE INDEX sales_daily_day_idx ON sales_daily (day);
SELECT * FROM sales_daily WHERE day = CURRENT_DATE;The index does not change when the base orders table changes. The stored rows change only when you refresh, and each refresh rebuilds the data and its indexes.
Refreshing without blocking readers using CONCURRENTLY
A plain REFRESH MATERIALIZED VIEW takes a lock that blocks readers until the refresh finishes. The CONCURRENTLY option builds the new contents alongside the old ones, so readers keep seeing the old rows until the swap completes.
CREATE UNIQUE INDEX sales_daily_day_uidx ON sales_daily (day);
REFRESH MATERIALIZED VIEW CONCURRENTLY sales_daily;Balancing data freshness against refresh cost
Between refreshes, readers see data that can be out of date. Each refresh reruns the full query, so frequent refreshes use more CPU and disk I/O. Choose the interval based on how old the data may be before it causes problems.
Exercise
Exercise
Why does a plain REFRESH MATERIALIZED VIEW block readers, and how does CONCURRENTLY avoid this?
Show answer
A plain refresh takes a lock that prevents reads until the new rows are written. CONCURRENTLY builds the new contents separately, so readers keep using the old rows, and PostgreSQL swaps in the new contents when the build finishes.