AI Hints
Home›PostgreSQL Tutorial›Views and Schemas
PostgreSQL · Lesson 71 of 120

Materialized Views

Save the results.

⏱ 2 min read▶ Video at 1:04:01🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

A view runs its query every time. For a heavy report, that's slow. A materialized view stores the results, like a cached table, and you refresh it when you want.

  • Heavy query
  • Store results
  • Refresh on demand

Store, then refresh

Create materialized view runs the query once, and saves the rows. A new order doesn't change it, until we refresh. Run it. Cooking revenue before and after the refresh.

query.sqlsql
CREATE MATERIALIZED VIEW genre_revenue_mv AS
SELECT b.genre, sum(i.quantity * b.price) AS revenue
FROM order_items i JOIN books b USING (book_id)
GROUP BY b.genre;
SELECT revenue FROM genre_revenue_mv WHERE genre = 'Cooking';

INSERT INTO order_items VALUES (1001, 9, 10);
SELECT revenue FROM genre_revenue_mv WHERE genre = 'Cooking';

REFRESH MATERIALIZED VIEW genre_revenue_mv;
SELECT revenue FROM genre_revenue_mv WHERE genre = 'Cooking';
Output
SELECT 9
 revenue
---------
 3762.46
(1 row)

INSERT 0 1
 revenue
---------
 3762.46
(1 row)

REFRESH MATERIALIZED VIEW
 revenue
---------
 4012.36
(1 row)

Materialized tips

Refresh concurrently lets people keep reading during a refresh, but needs a unique index. Refresh on a schedule, like every hour. And you can index a materialized view, like a table.

keyvalue
REFRESHrerun the query
CONCURRENTLYno blocking reads
Schedulecron, pg_cron
Indexesallowed

Summary

Materialized views store query results for speed, and refresh updates them. Next, schemas and the search path.

Key takeaways
  • MATERIALIZED
  • REFRESH
  • Cached
Next up: Schemas and search_path — folders for tables