Sub topic 12
Deciding When a Materialized View Is the Right Tool
Assume you know basic SELECT, JOIN, GROUP BY, aggregate functions, tables, views, and indexes. You should also understand that PostgreSQL stores table rows permanently, while a plain view stores only a query definition.
A materialized view stores the result of a query. PostgreSQL reads those stored rows when you query the materialized view. This can make expensive reports much faster, but the stored result becomes stale when the source tables change.
The main decision
A materialized view fits when all of these statements are mostly true:
- The query is expensive enough that running it repeatedly is a problem.
- Many users or applications read the same result.
- The result can be a few minutes or hours old.
- Rebuilding the result periodically costs less than running the original query for every reader.
- You can operate a refresh process and monitor failures.
The choice is a trade-off between read speed, freshness, storage, and refresh work.
Compare the common choices
A plain view is a stored query, not stored results. Each query against it runs the underlying query again. It provides current data, but it does not automatically make an expensive query faster.
A materialized view stores query results as rows. It can have indexes and can be queried like a table. PostgreSQL does not update those rows automatically. A refresh runs the defining query again and replaces the stored contents.
A table gives you the most control. Your application or a job can update it incrementally, but you must write and maintain the update logic.
| Choice | Freshness | Read speed | Maintenance |
|---|---|---|---|
| Plain view | Current at read time | Depends on base query | Low |
| Materialized view | Fresh only after refresh | Often fast | Scheduled or manual refresh |
| Summary table | As designed | Often fast | Application or job logic |
Measure refresh cost, not only query speed
Before choosing a materialized view, measure both the original query and a refresh. A fast read does not mean the design is cheap. A refresh may scan large tables, sort rows, compute aggregates, write the result, and update indexes.
For example, this query might be a good candidate if a dashboard runs it hundreds of times per hour but the business accepts hourly data:
SELECT order_date,
count(*) AS orders,
sum(total) AS revenue
FROM orders
GROUP BY order_date
ORDER BY order_date;A materialized view can reduce repeated work:
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_day_idx ON sales_daily (day);The index improves reads that filter or sort by day, but it also adds work during refresh and consumes storage. Add indexes that support real query patterns, not every possible column.
Evaluate freshness and blocking
Write down the actual freshness requirement. “Fast” is not a freshness requirement. Ask whether users need:
- Data current to the last transaction.
- Data no more than five minutes old.
- Data from the previous hour or day.
If every result must include the latest order, a materialized view may be the wrong choice. A plain view, an optimized query, or a summary table maintained as orders arrive may fit better.
A normal refresh can interfere with readers depending on the locks and workload involved. REFRESH MATERIALIZED VIEW CONCURRENTLY allows readers to continue using the existing contents while PostgreSQL builds the replacement. It requires a unique index that identifies every row, and it still consumes substantial CPU, I/O, and temporary space. It is not an incremental refresh.
Watch for failure modes
Materialized views become risky when teams forget that they are stale. Label dashboards with their last refresh time and alert when refresh jobs fail.
Other failure modes include:
- A refresh takes longer than the refresh interval, causing jobs to overlap.
- A source-table growth pattern makes refreshes increasingly expensive.
- An index makes reads faster but makes refreshes too slow.
- A refresh runs during peak traffic and competes for database resources.
- A query change requires dropping and recreating the materialized view, affecting dependent objects.
If the result must be updated continuously or only a small part changes at a time, a maintained summary table can avoid rebuilding all rows. That approach requires more application or job code, so compare its maintenance risk with the cost of full refreshes.
A practical decision rule
Choose a materialized view when read performance matters more than immediate freshness and the database can complete predictable refreshes within the allowed window. Start with one measured workload. Record query latency, refresh duration, row count, index size, and acceptable staleness. Reconsider the design when any of those values changes materially.
Exercise
A dashboard runs a five-minute aggregate query every minute. The business accepts data up to 15 minutes old, and the query result can be refreshed in two minutes. Is a materialized view a reasonable choice, and what should you monitor?
Show answer
Yes. The repeated query is expensive, the freshness requirement allows delayed data, and the refresh fits inside the 15-minute window. Monitor refresh duration, refresh failures, data age, database resource usage, overlapping jobs, and dashboard query latency.