Sub topic 11
Limitations and Alternatives to Built-in Materialized Views
This chapter assumes you can create, index, and refresh a materialized view, and that you know the difference between REFRESH MATERIALIZED VIEW and the CONCURRENTLY variant. It covers what the built-in feature cannot do and what you can use when it falls short.
What built-in materialized views cannot do
A PostgreSQL materialized view is a stored query result with a refresh command. That design is simple, and it has several consequences.
Refresh is always a full recomputation
REFRESH MATERIALIZED VIEW re-runs the whole defining query against the base tables. If orders holds 200 million rows and one row changed, the refresh still scans and aggregates all 200 million.
CONCURRENTLY does not change this. It builds the new result in a temporary area, compares it with the current contents, and applies only the differences. That reduces the lock on the view, not the work of computing the result. It adds work, because of the comparison.
Refresh cost therefore grows with the size of the base data, not with the size of the change.
Nothing refreshes automatically
PostgreSQL has no setting such as "refresh when the base tables change" or "refresh every ten minutes." You need a scheduler (pg_cron, system cron, or an application job) or a trigger that issues the refresh. Refreshing from a trigger on every write is usually a mistake, because each write would then pay for a full recomputation.
The view is read-only and its query is fixed
You cannot write to a materialized view:
UPDATE sales_daily SET revenue = 0 WHERE day = CURRENT_DATE;
-- ERROR: cannot change materialized view "sales_daily"There is also no CREATE OR REPLACE MATERIALIZED VIEW. ALTER MATERIALIZED VIEW can rename the view or its columns, change its owner or schema, set storage parameters, and so on. It cannot change the defining query. To change the query, drop the view and create it again. Any plain or materialized view that depends on it blocks the drop unless you use CASCADE, which drops those dependents too.
The planner does not use it automatically
Some other databases rewrite a query on base tables to read from a matching materialized view. PostgreSQL does not. If you write SELECT ... FROM orders GROUP BY order_date, the planner scans orders even if sales_daily holds the same answer. Queries must name the materialized view explicitly.
Locking and concurrency rules
| Command | Lock on the view | Readers during refresh | Requirements |
|---|---|---|---|
| `REFRESH MATERIALIZED VIEW` | `ACCESS EXCLUSIVE` | Blocked until the refresh commits | None |
| `REFRESH MATERIALIZED VIEW CONCURRENTLY` | `EXCLUSIVE` | Read the old contents | View is already populated. At least one unique index on plain columns with no `WHERE` clause. |
Under CONCURRENTLY, only one refresh of the same view can run at a time, and other writers to the view are blocked. Because it applies row-level inserts and deletes, it leaves dead tuples behind. Autovacuum has to clean these up, and a frequently refreshed large view can bloat.
The view also stores a second copy of the data in its own heap and indexes. For a wide, barely aggregated query, that storage can be as large as the source.
Privileges
Only the owner of a materialized view can refresh it. PostgreSQL 17 added a MAINTAIN privilege that can be granted to other roles for this purpose. On older versions, a scheduled job must run as the owner or call a SECURITY DEFINER function that does.
Choosing an alternative
The right alternative depends on which limitation hurts. Most of the time the limitation is either "refresh is too expensive" or "data is too stale."
Alternative 1: tune the query first
A materialized view is sometimes used to hide a missing index. Before adding one, run EXPLAIN (ANALYZE, BUFFERS) on the slow query. A composite index, a partial index, or an index-only scan can turn a multi-second query into a few milliseconds without any staleness. If the query is still slow after tuning, a materialized view is justified.
Alternative 2: a summary table maintained by triggers
A summary table is an ordinary table that you keep current yourself. A trigger applies each change to the summary row, so the cost is proportional to the change and the data is never stale.
This example keeps the same daily figures as sales_daily, using the orders table from earlier in the tutorial. The backfill and trigger creation run in one transaction. The lock prevents writes from slipping in between them.
CREATE TABLE sales_daily_summary (
day date PRIMARY KEY,
orders bigint NOT NULL,
revenue numeric(12,2) NOT NULL
);
CREATE FUNCTION orders_summary_apply() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP IN ('DELETE', 'UPDATE') THEN
UPDATE sales_daily_summary
SET orders = orders - 1,
revenue = revenue - OLD.total
WHERE day = OLD.order_date;
END IF;
IF TG_OP IN ('INSERT', 'UPDATE') THEN
INSERT INTO sales_daily_summary (day, orders, revenue)
VALUES (NEW.order_date, 1, NEW.total)
ON CONFLICT (day) DO UPDATE
SET orders = sales_daily_summary.orders + 1,
revenue = sales_daily_summary.revenue + EXCLUDED.revenue;
END IF;
RETURN NULL;
END;
$$;
BEGIN;
LOCK TABLE orders IN SHARE ROW EXCLUSIVE MODE;
INSERT INTO sales_daily_summary (day, orders, revenue)
SELECT order_date, count(*), sum(total)
FROM orders
GROUP BY order_date;
CREATE TRIGGER orders_summary_trg
AFTER INSERT OR UPDATE OR DELETE ON orders
FOR EACH ROW EXECUTE FUNCTION orders_summary_apply();
COMMIT;The function subtracts the old row's contribution on UPDATE and DELETE, and adds the new row's contribution on INSERT and UPDATE. Reads are plain SELECTs on a small, indexed table.
The costs are real:
- Every write to
ordersnow does extra work in the same transaction. - All concurrent writers for the same day update the same summary row. They queue on its row lock, so a busy day becomes a hot spot.
- You maintain the logic. Any new way of changing
ordersmust keep the summary correct.TRUNCATEdoes not fire row-level triggers, so it silently breaks the summary. - Days whose count drops to zero stay in the table as zero rows unless you clean them up.
- Aggregates such as
count(DISTINCT ...), medians, andmaxafter a delete cannot be maintained with simple arithmetic.
Alternative 3: a table rebuilt and swapped in
If you want full recomputation but need to control exactly when readers are affected, build a fresh table beside the live one and swap names:
BEGIN;
CREATE TABLE sales_daily_next AS
SELECT order_date AS day,
count(*) AS orders,
sum(total) AS revenue
FROM orders
GROUP BY order_date;
CREATE UNIQUE INDEX ON sales_daily_next (day);
DROP TABLE IF EXISTS sales_daily_tbl;
ALTER TABLE sales_daily_next RENAME TO sales_daily_tbl;
COMMIT;The slow part, building the new table, runs without locking the live one. Readers wait only between the DROP TABLE and the COMMIT. The cost is that you manage the swap yourself, and views that depend on the old table block the DROP. For many cases REFRESH ... CONCURRENTLY is simpler. This pattern is useful when you need to change the table definition or add a step such as ANALYZE before the swap.
Alternative 4: incremental view maintenance extensions
Extensions can add what the core feature lacks:
- pg_ivm provides incrementally maintainable materialized views. It updates the view as base tables change, applying only the delta. It supports a limited set of query shapes, and it must be installed on the server. Managed database services may not offer it.
- TimescaleDB continuous aggregates maintain time-bucketed aggregates incrementally for time-series data. They suit append-heavy tables and come with the TimescaleDB extension.
Check which extensions your host supports, which query features they accept, and how the write overhead compares to your needs before building on one.
Alternative 5: move the work elsewhere
- Application or external cache. Store the result in Redis or in application memory with a time-to-live. This is easy when exact consistency is not needed. You lose the ability to query the result with SQL.
- Read replica. A heavy reporting query can run on a streaming replica, so it does not compete with transactional traffic. The query is still slow, but it affects fewer users.
Comparing the options
| Approach | Freshness | Write overhead | Read speed | Maintenance effort |
|---|---|---|---|---|
| Plain view | Always current | None | As slow as the query | None |
| Materialized view | As of last refresh | None | Fast | Low: a schedule |
| Trigger-maintained table | Always current | Per write | Fast | High: your code |
| Rebuild and swap table | As of last rebuild | None | Fast | Medium: swap script |
| Incremental extension | Near-current | Per write | Fast | Medium: extension upkeep |
Common mistakes
- Refreshing from a trigger on every write. Each insert then runs the full aggregate. Use a schedule, or maintain a summary table instead.
- Forgetting the unique index.
CONCURRENTLYfails without one, and the failure shows up at refresh time, often in a scheduled job that nobody is watching. - Assuming
CONCURRENTLYis always better. On a small view, a plain refresh is faster and the lock is brief. The concurrent variant pays for the comparison and leaves dead tuples. - Expecting the planner to use the view. Queries must reference the materialized view by name.
- Ignoring bloat and dependencies. Monitor the view's size with
pg_total_relation_size, and check dependent views before dropping.
Exercise
Your sales_daily view takes 4 minutes to refresh, and the business now needs revenue figures that are never more than a few seconds old. The orders table receives mostly inserts, a few hundred per second, spread across many dates. Name one built-in approach that does not meet the requirement and explain why. Then name a better approach and one risk it carries.
Show answer
Scheduling REFRESH MATERIALIZED VIEW CONCURRENTLY more often does not work. Each refresh recomputes the whole aggregate, so it takes 4 minutes regardless of how few rows changed, and the data can be minutes old. A trigger-maintained summary table (or an incremental extension such as pg_ivm) applies only each change, so it stays current. The risks are extra work on every insert into orders, row-lock contention if many writers update the same day's summary row, and logic that is wrong if the trigger misses a case such as TRUNCATE. Because inserts are spread across many dates, contention is lower than if they all hit one day.
Exercise
You need to change the GROUP BY in a materialized view that two other views depend on. Which commands can you not use, and what is the usual way to make the change safely?
Show answer
You cannot use CREATE OR REPLACE MATERIALIZED VIEW, which does not exist, and ALTER MATERIALIZED VIEW, which cannot change the query. Drop and recreate the view. Plain DROP fails because of the dependent views, so inspect them first. Then either drop with CASCADE and recreate all of them, or recreate the dependent views from their saved definitions inside one transaction, so readers never see a missing object. Recreate the indexes on the new view as well.