Sharon Ben-Moshe is the founder of sqlfmt, a browser-based SQL formatter and validator with misspelled-keyword suggestions across PostgreSQL, MySQL, SQLite, SQL Server, and BigQuery.
Learn how to cache complex analytical queries with PostgreSQL materialized views. Master REFRESH MATERIALIZED VIEW CONCURRENTLY, indexing, and scheduling.
Quick answer
PostgreSQL materialized views persist the query results of a SELECT statement physically on disk as a table, allowing instant reads for heavy analytical queries. Adding a unique index enables REFRESH MATERIALIZED VIEW CONCURRENTLY, refreshing cached data in the background without acquiring exclusive table locks or blocking reader queries.
FAQs
Why does REFRESH MATERIALIZED VIEW CONCURRENTLY throw an error about a unique index?
PostgreSQL requires a unique index across non-nullable columns to identify and apply row-level differences between the old and newly computed dataset during a concurrent refresh.
Does PostgreSQL automatically update materialized views when table data changes?
No. Materialized views in PostgreSQL do not update automatically. You must run REFRESH MATERIALIZED VIEW manually or schedule it via cron.
Is REFRESH CONCURRENTLY slower than standard REFRESH?
Yes. Concurrent refresh takes slightly longer and uses more temporary disk space because it computes differences and updates rows individually to avoid locking readers.
Can I create a materialized view without populating data immediately?
Yes. Append WITH NO DATA to the creation statement. The view will be created as an empty structure until you issue your first REFRESH command.
Build fast text search directly in PostgreSQL without external search engines. Master to_tsvector, to_tsquery, relevance ranking with ts_rank, and GIN indexes.
Complex reporting queries that join dozens of tables, compute rolling aggregations, and process millions of rows can easily take 15 to 30 seconds to execute. Running these expensive queries on live transactional tables every time a user loads a dashboard causes connection exhaustion, CPU spikes, and sluggish page loads.
Standard SQL views do not cache data; they are simply saved query text expanded at execution time. PostgreSQL materialized views solve this problem by storing the query result physically on disk as an actual table. Reading the materialized view is as fast as querying a pre-indexed table.
Standard views vs materialized views
Review the difference between virtual and physical views:
Standard view (CREATE VIEW): The database stores only the query definition. Every time a client queries the view, PostgreSQL executes the underlying query from scratch. Read our guide to SQL view formatting and best practices for structure tips.
Materialized view (CREATE MATERIALIZED VIEW): PostgreSQL executes the query once and saves the resulting dataset to disk. Queries scan the persisted data instantly, but the data does not update automatically when underlying tables change.
Creating and indexing a materialized view
You define a materialized view with standard SQL. Because a materialized view behaves like a physical table, you can create B-tree and GIN indexes on its columns.
Creating an analytical materialized view with indexes
-- Create materialized view aggregating monthly sales metricsCREATE MATERIALIZED VIEW mv_monthly_regional_revenue ASSELECT r.region_id, r.region_name, DATE_TRUNC('month', o.order_date)::DATE AS sales_month, COUNT(o.order_id) AS total_orders, SUM(o.total_amount) AS gross_revenue, AVG(o.total_amount) AS average_order_valueFROM regions rJOIN customers c ON c.region_id = r.region_idJOIN orders o ON o.customer_id = c.customer_idWHERE o.order_status = 'completed'GROUP BY r.region_id, r.region_name, DATE_TRUNC('month', o.order_date);-- Create unique index (REQUIRED for CONCURRENT refresh!)CREATE UNIQUE INDEX uq_mv_monthly_revenueON mv_monthly_regional_revenue (region_id, sales_month);-- Create secondary index for fast range filteringCREATE INDEX idx_mv_monthly_revenue_monthON mv_monthly_regional_revenue (sales_month DESC);
According to the PostgreSQL materialized views guide, queries against mv_monthly_regional_revenue now execute in under two milliseconds using standard index seeks.
The blocking refresh problem and REFRESH CONCURRENTLY
To update a materialized view with recent data, you issue the REFRESH MATERIALIZED VIEW command. By default, standard refresh acquires an ACCESS EXCLUSIVE lock on the materialized view.
While the refresh runs, all SELECT queries against the view are blocked. If your refresh takes 45 seconds to recompute, dashboards reading the view freeze for 45 seconds. In production, this causes HTTP gateway timeouts.
To refresh the view without blocking readers, use REFRESH MATERIALIZED VIEW CONCURRENTLY. Under concurrent refresh, PostgreSQL computes the new dataset in a temporary table, compares differences against the current table, and issues internal insert, update, and delete statements. Existing readers continue to read the old data without locking!
Refreshing a materialized view concurrently
-- Standard refresh: BLOCKS ALL READERS!-- REFRESH MATERIALIZED VIEW mv_monthly_regional_revenue;-- Concurrent refresh: Non-blocking, reads continue normally!REFRESH MATERIALIZED VIEW CONCURRENTLY mv_monthly_regional_revenue;
Automating refreshes with pg_cron or external schedulers
Because PostgreSQL does not automatically update materialized views, you must schedule refreshes periodically using a cron runner or database extensions like pg_cron.
Scheduling automated refreshes with pg_cron
-- Schedule hourly concurrent refresh via pg_cron extensionSELECT cron.schedule( 'refresh-monthly-revenue-mv', '0 * * * *', -- Every hour on the hour 'REFRESH MATERIALIZED VIEW CONCURRENTLY mv_monthly_regional_revenue');
Actionable checklist for PostgreSQL materialized views
Create a UNIQUE index: always define a unique index on the primary key combination to allow CONCURRENT refreshes.
Use REFRESH CONCURRENTLY in production: avoid plain REFRESH to prevent ACCESS EXCLUSIVE reader locks.
Index frequently filtered columns: add secondary indexes on dates and IDs just as you would on standard tables.
Tune work_mem for refresh jobs: ensure sufficient work_mem is allocated for the session performing the refresh aggregation.
Automate scheduling: use pg_cron, Airflow, or cron to trigger refreshes during predictable intervals.
Inspect execution plans: run EXPLAIN ANALYZE on the view to ensure queries use the created indexes.
Wrapping up
PostgreSQL materialized views deliver sub-millisecond query performance for complex reports by precomputing and persisting results on disk. By adding a unique index and scheduling non-blocking concurrent refreshes, you protect production database concurrency while speeding up user-facing dashboards. Format your analytical queries and view DDL scripts with sqlfmt for clean team reviews.