ReinDBby Bandlei

10. Materialized views and partitioning

Brett Rosenblatt · Database tuning guide v1.3 · PDF

Both techniques trade extra design and maintenance for faster reads and easier data management. Both are frequently misused: materialized views as a substitute for fixing a query, partitioning as a magic speed switch. Used for the right reasons, they are two of the most effective tools in this guide.

10.1Materialized views: precomputed answers

A materialized view (MV) stores the result of a query as a table and refreshes it on a schedule or as the base data changes.

Use one when:

  • An expensive aggregation or join is read far more often than its base data changes.
  • Readers can accept data that is a little stale (minutes or hours), or the engine can keep it current cheaply.
  • Dashboards and reports hit the same summary again and again.
  • You need a local copy of remote or slowly changing reference data.

Avoid one when the base data changes constantly and readers need it exact; when the real problem is a missing index or a bad query; or when the refresh would cost more than the reads it saves.

Support differs widely by engine

EngineWhat you get
PostgreSQLCREATE MATERIALIZED VIEW with full refresh only. REFRESH ... CONCURRENTLY avoids blocking readers but requires a unique index on the MV. No incremental refresh in core (third-party extensions exist) and no query rewrite: queries must name the MV
MySQLNo materialized views. Use summary tables maintained by scheduled events, triggers or your ETL
SQL ServerIndexed views: a view with SCHEMABINDING and a unique clustered index, maintained synchronously with every change to the base tables. The optimizer matches them automatically only in Enterprise Edition; other editions must reference the view with WITH (NOEXPAND). Many restrictions (no outer joins, deterministic expressions only, COUNT_BIG(*) required with GROUP BY, specific SET options)
OracleThe fullest implementation: complete or fast (incremental) refresh, on demand or on commit; materialized view logs to track changes; query rewrite, so the optimizer can answer queries against base tables from an MV automatically; DBMS_MVIEW.EXPLAIN_MVIEW to see why fast refresh isn't possible; real-time materialized views (12.2+). Query rewrite requires Enterprise Edition

Examples

Materialized view pitfalls

  • Refresh cost and locking. A full refresh of a large MV can take longer than the queries it saves, and some refresh modes block readers.
  • Stale data surprises. Make the refresh time visible to users ("data as of 06:00").
  • On-commit refresh slows writers. Views maintained inside every transaction add work to each change on the base tables, and can become a source of contention and deadlocks on busy tables.
  • Growing change logs. Where incremental refresh reads a change log, a view that stops refreshing keeps the log from being purged, and it grows without limit.
  • Missing statistics and indexes. An MV is a table: gather statistics on it and index it for the queries that read it.
  • Dependency chains. MVs built on MVs must refresh in order; a failure in the middle leaves an inconsistent set.

10.2Partitioning: one table, many pieces

Partitioning splits a table (and usually its indexes) into pieces by a key: ranges of dates, lists of values, or a hash.

What it gives you:

  • Partition pruning: queries that filter on the partition key read only the relevant partitions.
  • Cheap data lifecycle: drop, truncate, detach or exchange a whole partition in seconds instead of running a huge DELETE.
  • Maintenance per partition: gather statistics, rebuild indexes, compress or move one partition at a time; old partitions can live on cheaper storage.
  • Partition-wise joins and parallelism for large analytic queries.

What each engine offers

EngineNotes
PostgreSQLDeclarative partitioning (10+): range, list, and hash (11+); a default partition (11+); indexes on the parent cascade to partitions (11+); foreign keys referencing partitioned tables (12+); DETACH PARTITION ... CONCURRENTLY (14+). Primary keys and unique constraints must include the partition key. Execution-time pruning (11+) helps prepared statements. The pg_partman extension automates creating and retiring partitions
MySQLRange, list, hash and key partitioning, plus RANGE COLUMNS and LIST COLUMNS. Every unique key, including the primary key, must include all partitioning columns. Partitioned InnoDB tables can't have foreign keys, in either direction. Up to 8,192 partitions. ALTER TABLE ... EXCHANGE PARTITION and DROP PARTITION are fast
SQL ServerA partition function and a partition scheme; available in all editions since 2016 SP1. Keep indexes aligned with the table. ALTER TABLE ... SWITCH moves a whole partition in or out instantly; TRUNCATE TABLE ... WITH (PARTITIONS (...)) (2016+) empties one; up to 15,000 partitions per table
OracleA separately licensed option of Enterprise Edition. Range, list, hash and composite partitioning; interval partitioning (11g) creates new partitions automatically; reference partitioning (11g). 12c added partial indexes and online partition moves; 12.2 added online conversion of a regular table to a partitioned one, auto-list partitioning and filtered partition maintenance; 19c added hybrid partitioned tables. Local indexes are partitioned with the table; global indexes need maintenance when partitions are dropped (UPDATE INDEXES; asynchronous global index maintenance in 12c+)

Examples: monthly partitions by order date

Choosing the partition key and size

  • Choose the column that most important queries filter on and that defines the data lifecycle. For transactional data that is nearly always a date.
  • Size partitions so a typical query touches one or a few, and so the number of partitions stays manageable: tens to low thousands, not tens of thousands. Daily partitions for seven years of data is usually too many; monthly is often right.
  • Create future partitions ahead of time (or let the engine or a scheduled job do it), and monitor that the job runs. A missing partition means failed inserts, or rows piling into a default partition.

Partitioning pitfalls

  • A key that queries don't filter on, so nothing is pruned.
  • Too many tiny partitions, which inflates planning time and metadata.
  • Unique constraints that must now include the partition key, which changes what "unique" means.
  • Maintenance of global (non-partitioned) indexes when partitions are dropped or exchanged.
  • Statistics on partitioned tables. Table-level statistics can need a rescan of every partition, or may not be kept up to date automatically (see the engine note).
  • Functions or type conversions on the partition key in predicates, which defeat pruning just as they defeat indexes.
  • A hot current partition that takes all the writes, while old partitions sit idle. That is normal, but size storage and indexes for it.

10.3Using them together

Partitioning and materialized views combine well for time-series data:

  • Partition the summary too. A daily or monthly summary partitioned by date can be refreshed one recent partition at a time.
  • Load by swapping. Build the new period's data or summary in a separate table, then swap it into the partitioned table in one quick metadata operation.

10.4Which tool for which problem?

ToolSolvesCostsDon't use it for
IndexFinding few rows fast; ordering; covering hot queriesWrite overhead, storageQueries that read most of the table
Materialized view or summary tableRepeated expensive aggregations and joinsRefresh work, staleness, storageData that must always be exact and changes constantly
PartitioningData lifecycle, maintenance per piece, pruning on the keyDesign constraints, more objects to manage, sometimes a licenseSpeeding up queries that don't filter on the key
Columnstore or columnar tierScans and aggregates over very many rowsSlower single-row access, load patternsOLTP lookups
Archiving or tiering (Chapter 4)Storage, backup time, maintenance windowsMoving data, cross-tier queriesData that is still hot

This is one chapter of the free database tuning guide for PostgreSQL, MySQL, SQL Server and Oracle. Download the whole guide as a PDF.