Stop 13 · Views, Procedures & SecurityTopics · 2/9

Materialized Views

Part of the SQL Roadmap

In short

Some dashboard queries join and group millions of rows every time someone opens the page. A materialized view does that heavy work once, stores the answer and serves it instantly.

A materialized view stores the result of a query on disk so reads are fast, but it must be refreshed to pick up new data. PostgreSQL supports it with REFRESH MATERIALIZED VIEW; MySQL has no built-in version, so a summary table is used instead.

The jaadu lifts the lid off a huge steaming copper handi of biryani and quickly fills a line of plates held out by hungry customers.

Think of it like this

The big handi of biryani

A busy biryani place in Hyderabad doesn't cook each plate to order. It cooks a big handi at noon and serves plates from it in seconds. The catch: every plate is from the noon batch until they cook a fresh handi. A normal view cooks to order every time. A materialized view is the handi, fast to serve and only as fresh as its last refresh.

Watch it happen

View vs materialized view

View

  • Stores only the query text
  • Runs the full query on every read
  • Always up to date
  • Slow if the query is heavy

Materialized view

  • Stores the result rows on disk
  • Reads are as fast as a small table
  • Stale until REFRESH runs
  • Can have its own indexes

Use a materialized view for heavy summaries that can be a little out of date, like yesterday's sales by city. Use a normal view when results must be live.

The big ideas

What you need to know

Pre-computed results

The query runs once at creation and again at each refresh. Reads just scan the stored rows.

Refresh on a schedule

REFRESH MATERIALIZED VIEW re-runs the query. Schedule it hourly or nightly with cron, pg_cron or your ETL tool.

CONCURRENTLY keeps it readable

A plain refresh blocks readers. CONCURRENTLY doesn't, but needs a unique index on the view.

MySQL has none

MySQL has no materialized views. Build a summary table and refresh it with a scheduled event instead.

See it in code

Walk through the code

sql
1CREATE MATERIALIZED VIEW city_daily_sales AS2SELECT c.city,3       o.order_date,4       COUNT(*)      AS orders,5       SUM(o.amount) AS revenue6FROM orders o7JOIN customers c ON c.customer_id = o.customer_id8GROUP BY c.city, o.order_date;9 10-- Needed for CONCURRENTLY, and speeds up lookups11CREATE UNIQUE INDEX uq_city_daily_sales12  ON city_daily_sales (city, order_date);13 14-- Fast: no join or GROUP BY at read time15SELECT order_date, revenue16FROM city_daily_sales17WHERE city = 'Hyderabad'18ORDER BY order_date DESC19LIMIT 7;20 21-- Pick up new orders without blocking readers22REFRESH MATERIALIZED VIEW CONCURRENTLY city_daily_sales;

1/4The heavy query: join plus GROUP BY over all orders. It runs now and its result is saved.

PostgreSQL syntax. SQL Server has indexed views, which update automatically but come with many restrictions. In MySQL, use a summary table filled by INSERT ... SELECT.

Save yourself the pain

Common mistakes

Oops

Creating a materialized view and never refreshing it.

Do this instead

Set up a scheduled refresh and show 'data as of' time on the dashboard.

Oops

Using REFRESH ... CONCURRENTLY without a unique index.

Do this instead

PostgreSQL will refuse. Create a unique index on the columns that identify each row first.

Your mission

Cache a dashboard query

~25 min

Quick check

You inserted 100 new orders. Why doesn't your materialized view show them yet?

Go deeper

  1. 1Create a materialized view for a slow monthly revenue summary in PostgreSQL.
  2. 2Refresh it and compare query time with the plain view.
  3. 3Decide how often the data needs to be fresh before choosing a refresh schedule.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge