Lompat ke konten

Pelajaran 20 ยท Querying and Performance

Materialized Views and Aggregate Tables

Use views, materialized views and aggregate tables wisely: refresh strategies, incremental refresh with late data, additive designs and reconciliation.

If hundreds of people open the same dashboard, calculating the same totals from billions of detail rows each time is wasteful. You can precompute them. The price is that a stored result can become out of date, so every precomputed object needs a refresh plan.

Three kinds of object

Object Stores results? Freshness
View No; it is a saved query Reflects its tables at query time
Materialized view Yes; managed by the database Depends on its refresh behavior
Aggregate (summary) table Yes; managed by your pipeline Depends on your job

Support for materialized views varies widely. Some platforms refresh them automatically or incrementally; others refresh only when you ask. Many restrict which SQL is allowed. Some optimizers can rewrite a query on detail tables to use a matching materialized view, but do not assume yours does.

SQL
-- Read-only: PostgreSQL syntax; refresh is a separate command there
CREATE MATERIALIZED VIEW mv_daily_sales AS
SELECT sale_date, store_key, SUM(amount) AS revenue
FROM fact_sales
GROUP BY sale_date, store_key;

REFRESH MATERIALIZED VIEW mv_daily_sales;

SQLite has no materialized views, so the next example uses a table that we refresh ourselves.

See a result go stale

SQL Stand-in: an aggregate table that goes stale

Press Run (or Ctrl + Enter) to see the result here.

Notice that refreshing "only today" would have missed the late row for 1 October. Your pipeline needs to know which periods changed, for example from load timestamps on the facts. In a real job, run the delete and insert in one transaction.

Design aggregates that can be rolled up

An aggregate is reusable when its measures can be combined further:

  • Sums and counts roll up.
  • Minimum and maximum can be combined with new values, but deletes or corrections may force recalculation.
  • Averages do not roll up. Store the sum and the count.
  • Distinct counts do not simply add; recount from detail or use a mergeable approximate structure if your platform has one.

These follow directly from additivity.

SQL Averages: store the parts

Press Run (or Ctrl + Enter) to see the result here.

The first result is 200, but the real average order is about 118.18.

Which aggregates to build

Let real usage guide you:

  1. Find the queries that are slow, frequent or expensive.
  2. Look for shared groupings, such as day by store by category.
  3. Choose a grain that serves several of them.
  4. Estimate how much smaller it is than the detail. An aggregate with nearly as many rows as the detail helps little.
  5. Compare the savings with the cost of storage, refresh compute and maintenance.
  6. Review periodically and remove what nobody uses.

Aggregates should use the same conformed dimensions, or shrunken versions of them. Give them clear names, such as agg_sales_day_store.

History and rebuilds

Decide how aggregates behave when a dimension changes. If you group by a Type 1 attribute such as the current category, an update to a product's category changes how past sales should be summarized, and stored aggregates must be rebuilt. Aggregates keyed by surrogate keys and joined at query time handle this more gracefully.

Other caching layers

Platforms may cache query results, and BI tools often keep their own extracts. Each layer adds speed and another place where old data can appear. Show a "data as of" timestamp on important dashboards, taken from the data itself.

Reconcile

After each refresh, compare totals between detail and aggregate for the refreshed periods. Alert on differences beyond what you can explain.

Full or incremental refresh?

Strategy Strength Cost
Full rebuild Simple, picks up every correction Work grows with the whole history
Replace changed periods Much less work Must detect every affected period
Add the new values to stored totals Very little work Reruns can double count; updates and deletes are hard

Prefer the first while it is fast enough. The second is a good next step. Be careful with the third: unless each batch is applied exactly once, a retry corrupts totals without any error message. Even with incremental refresh, schedule an occasional full comparison or rebuild.

Publish without gaps

If a rebuild drops a table and then creates it again, a dashboard query that arrives in between can fail or see partial data. Safer options include running the change in a transaction, or building a new table beside the old one, checking it and switching a view or table name in one short step. What is atomic depends on the platform, so test the behavior rather than assuming it.

Dependencies and order

Aggregates often feed other aggregates. Refresh them in dependency order and stop downstream refreshes when an upstream one fails. Otherwise a monthly table can be "refreshed successfully" from yesterday's daily table. Record for each object which source data it includes, for example the latest load batch. A refresh time alone can mislead: a table can be refreshed a minute ago from stale input.

When not to precompute

If a query is rare, already quick enough or varies in many unpredictable ways, an aggregate adds work without much benefit. Exploratory analysis usually belongs on the detail tables. Result caching offered by the platform may already cover repeated identical queries.

Document each aggregate

For every stored summary, record its grain, source tables, filters, refresh method and owner. Say how late data is handled, so that readers know whether last week's figures can still move.

Common mistakes

Creating many overlapping summaries "to make things fast" gives you several versions of the same number with different refresh times. Fewer, well-maintained aggregates are easier to trust.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. What is the key difference between a view and a materialized view?

    Stored results are faster to read but depend on refresh behavior.
  2. 2. Which should an aggregate store so that averages can be rolled up correctly?

    The overall average is the total sum over the total count.
  3. 3. Why might refreshing only the newest date be wrong?

    The refresh must cover every period that changed.

Summary

  • Views store queries; materialized views and aggregate tables store results.
  • Every stored result needs a refresh strategy that includes late and corrected data.
  • Store additive parts so results can be rolled up.
  • Build aggregates from real usage, reconcile them and retire unused ones.

Next: Data Quality and Reconciliation

Progres Anda disimpan di browser ini. Tidak perlu akun.