Materialized Views

Precomputed query results stored as tables. PostgreSQL refresh strategies, indexes on materialized views, and when to use them vs views or denormalization.

published: reading time: 26 min read author: Geek Workbench
Quick Summary

Materialized views store query results for faster reads, with refresh behavior varying by database. This guide compares PostgreSQL 18 full refreshes with Oracle Database 26ai fast, complete, and on-commit refresh options, then shows how to set a freshness target and choose a refresh strategy for append-only or mutable data.

Materialized Views

A regular view is a stored query. When you query it, the database runs the underlying query and returns the result. No data is stored. Every query to the view re-executes the query.

A materialized view stores the actual result. The query runs once, the result is saved as a table, and you query that table directly. Fast reads, stale data.

The tradeoff between freshness and refresh cost determines whether a materialized view fits.

Introduction

A regular view runs its underlying query every time you query it. A materialized view runs its underlying query once, stores the result as a table, and serves that result on subsequent queries. The tradeoff is freshness: a materialized view can serve an older result, while a regular view evaluates its query against current table data.

This guide uses PostgreSQL 18 and Oracle Database 26ai syntax. Their refresh features differ: PostgreSQL’s REFRESH MATERIALIZED VIEW CONCURRENTLY is still a full refresh, while Oracle can perform fast refreshes when a view definition and materialized view logs meet its requirements. Check the documentation for the database version you deploy.

Materialized Views vs Regular Views vs Denormalization

Regular views are logical constructs. They don’t store data, just the query definition. Use them for hiding complex queries, restricting access without separate tables, or encapsulating business logic.

Materialized views store precomputed results. They can help when a repeated query is expensive and the application can tolerate the refresh delay.

Denormalization duplicates data manually. Your code decides what to store and how to keep copies in sync. A materialized view stores the result of a query, but still needs an explicit refresh policy.

PostgreSQL Materialized Views

PostgreSQL 18 stores a materialized view’s query result in a table-like relation. Creating one with WITH DATA runs the query immediately; WITH NO DATA leaves it unpopulated until a later refresh.

CREATE MATERIALIZED VIEW sales_by_month AS
SELECT
    date_trunc('month', order_date) AS month,
    customer_id,
    SUM(total) AS total_sales
FROM orders
GROUP BY date_trunc('month', order_date), customer_id
WITH DATA;

WITH DATA populates the view immediately. Without it, you create an empty view that populates on first refresh.

Query the materialized view like a regular table:

SELECT * FROM sales_by_month WHERE month >= '2025-01-01';

Refreshing Materialized Views

Data goes stale as underlying tables change. PostgreSQL offers two refresh strategies:

Full refresh rewrites the entire materialized view:

REFRESH MATERIALIZED VIEW sales_by_month;

This replaces the stored contents. Reads of the materialized view are blocked while this refresh runs.

Concurrent refresh rebuilds without blocking reads:

REFRESH MATERIALIZED VIEW CONCURRENTLY sales_by_month;

CONCURRENTLY keeps readers from being blocked by the refresh. It requires an already populated materialized view and a qualifying unique index over column names that covers all rows. It does not compute only changed rows: PostgreSQL still reruns the defining query and reconciles the result. Only one refresh at a time can run for a given materialized view.

CREATE UNIQUE INDEX ON sales_by_month (month, customer_id);

The two modes have different locking and resource tradeoffs. Measure them with the real query and workload before choosing one.

Automatic Refresh

PostgreSQL 18 does not schedule refreshes automatically. Use an external scheduler or an extension such as pg_cron to run a full refresh on a writable primary. Physical standbys receive the refreshed contents through WAL replay; they cannot independently refresh a materialized view.

Scheduled refresh via pg_cron. pg_cron runs SQL directly inside the database, so you can schedule refreshes without external tooling:

-- Refresh every hour at the top of the hour
SELECT cron.schedule('refresh-sales-mv', '0 * * * *',
 'REFRESH MATERIALIZED VIEW CONCURRENTLY sales_by_month');

-- Refresh daily at 3am
SELECT cron.schedule('refresh-daily-stats', '0 3 * * *',
    'REFRESH MATERIALIZED VIEW CONCURRENTLY daily_stats');

pg_cron uses cron-style schedules and runs SQL on the configured PostgreSQL instance. Use one scheduler against the writable primary for a physical-replication setup. PostgreSQL permits only one refresh at a time for a given materialized view; concurrent refresh does not make duplicate jobs independent.

Trigger-based change capture. A trigger can record changed keys or rows in a queue for a separate worker. That queue does not make PostgreSQL’s built-in materialized-view refresh incremental: REFRESH MATERIALIZED VIEW still reruns the full defining query. To update only affected keys or ranges, maintain a separate summary table and implement its insert, update, delete, retry, and reconciliation behavior explicitly.

The problem with this approach: triggers add work to writes. Keep the trigger small and measure its effect. This pattern is most suitable when the system can tolerate the extra write-path work and the queue has retry, idempotency, and reconciliation behavior.

Application-level refresh. After any write to the underlying tables, the application calls REFRESH MATERIALIZED VIEW. This keeps the MV fresh for data that just changed, useful when users need to see their own recent data without waiting for a scheduled refresh.

The downside: a refresh in the write path reruns the defining query and can extend transaction latency. Moving the refresh to a background job changes the freshness guarantee but not the fact that the built-in refresh is full. If an application needs per-key or per-range updates, use a custom summary table or another incremental pipeline.

PostgreSQL does not refresh a materialized view automatically when its source tables change. Schedule a full refresh with an external job or an extension such as pg_cron; do not assume that concurrent refresh is incremental maintenance.

Oracle Materialized Views

This section uses Oracle Database 26ai terminology. Oracle materialized views support several refresh methods, but fast refresh is available only when the view definition and its change logs satisfy Oracle’s requirements.

  • On-commit refresh, when the view supports it
  • Refresh groups for keeping related views transactionally consistent
  • Query rewrite, when enabled and the optimizer can use the view
CREATE MATERIALIZED VIEW monthly_sales
BUILD IMMEDIATE
REFRESH FAST ON COMMIT
AS
SELECT
    EXTRACT(YEAR FROM order_date) AS year,
    EXTRACT(MONTH FROM order_date) AS month,
    SUM(total) AS total_sales
FROM orders
GROUP BY EXTRACT(YEAR FROM order_date), EXTRACT(MONTH FROM order_date);

BUILD IMMEDIATE populates the view during creation. REFRESH FAST ON COMMIT asks Oracle to maintain it from logged changes at commit time; use this only after checking fast-refresh eligibility for the exact query and base tables.

Refresh Methods

Oracle’s ALL_MVIEWS.REFRESH_METHOD lists four refresh methods: FAST, COMPLETE, FORCE, and NEVER. The method describes how refresh work is done; REFRESH_MODE controls when refreshes occur (COMMIT, DEMAND, STATEMENT, or NEVER). See the Oracle Database 26ai ALL_MVIEWS reference.

REFRESH FAST applies changes from materialized view logs when the query supports fast refresh. Create and configure the required logs on the base tables; Oracle does not create them automatically just because a materialized view exists. Check the Oracle Database 26ai refresh guide before relying on a particular aggregate or join.

Fast refresh has limitations. The MV query must be simple enough for Oracle to compute the delta. SUM, COUNT, AVG, MIN, MAX, and some join patterns typically work. Complex queries with arbitrary subqueries, DISTINCT, or set operations often cannot use fast refresh. If you try REFRESH FAST on an unsupported MV, Oracle returns an error. Check SELECT mview_name, refresh_mode, refresh_method FROM user_mviews to see which MVs support fast refresh.

REFRESH COMPLETE rewrites the entire MV from scratch. No MV logs are required. This is the default if you do not specify. Use it when the MV query is too complex for fast refresh, when the underlying data changes in ways that make delta computation difficult, or when you want a clean rebuild to reclaim fragmentation. The cost scales with the total MV size, not the delta.

REFRESH FORCE attempts fast refresh and falls back to complete refresh when fast refresh is unavailable. That fallback can change refresh duration sharply, so monitor the method actually used instead of treating FORCE as a performance guarantee.

REFRESH NEVER records that Oracle should not refresh this materialized view. Use it only when that behavior is intentional; the stored results can become stale as the base tables change.

For eligible fast refreshes, create the required materialized view logs on base tables. Exact columns and options depend on the view definition:

CREATE MATERIALIZED VIEW LOG ON orders
WITH ROWID, SEQUENCE (order_date, customer_id, total)
FORCE LOGGING;

Oracle’s refresh documentation describes supported log options and cleanup behavior. Validate log requirements against the actual query rather than copying this example unchanged.

Set a freshness target before scheduling refreshes

An SLA should state how old a result may be, what users see during refresh, and what happens when a refresh misses its deadline. The schedule is a design choice, not a guarantee that the view is that fresh.

Maximum acceptable age Typical starting point Operational check
Seconds to a few minutes Consider on-commit or eligible fast refresh in Oracle; PostgreSQL materialized views may be a poor fit if full-query refresh cannot meet the target Measure write impact, refresh duration, and staleness under peak load
Tens of minutes to a few hours Schedule refreshes and publish the last successful refresh time Alert when age exceeds the target; define behavior for a missed run
Daily or longer Batch refresh after source data is complete Record the data cutoff and rerun policy

The ranges are planning categories, not database guarantees. Pick the maximum age with the people who use the result, then measure the chosen refresh process.

Worked strategy: append-only and mutable data

Suppose a report groups orders by day and customer. For append-only, closed daily partitions, refresh the report after each partition is loaded and validated. If the report can tolerate a delay, batch refresh once after the load rather than refreshing for every inserted row. Keep a watermark for the latest complete source date and expose it beside the report.

Mutable orders need a different plan because updates and deletes can change earlier groups. In PostgreSQL 18, plan and measure a full REFRESH MATERIALIZED VIEW or ... CONCURRENTLY run; the concurrent form protects readers but still reevaluates the query. If the required freshness cannot be met, use a maintained summary table or another incremental pipeline instead. In Oracle 26ai, check whether the query and materialized view logs support FAST refresh, then test update and delete cases as well as inserts. For both databases, run a full refresh periodically if the recovery plan requires reconciliation against source data.

PostgreSQL references: materialized views and REFRESH MATERIALIZED VIEW. Oracle reference: read-only materialized view concepts.

Indexes on Materialized Views

Materialized views are tables. Index them like regular tables to speed up queries.

CREATE MATERIALIZED VIEW order_summary AS
SELECT
    customer_id,
    status,
    COUNT(*) AS order_count,
    SUM(total) AS total_value
FROM orders
GROUP BY customer_id, status;

CREATE INDEX idx_order_summary_customer ON order_summary (customer_id);
CREATE INDEX idx_order_summary_status ON order_summary (status);

For frequently filtered queries, test whether an index on the materialized result improves the plan.

Oracle supports bitmap indexes on materialized views, which compress well for low-cardinality columns like status flags.

When Materialized Views Make Sense

Materialized views work when:

  • Underlying data changes infrequently compared to query frequency
  • Queries are expensive aggregations or multi-table joins
  • You can tolerate stale data for a known period
  • Query patterns are predictable and stable

Analytics workloads fit well. Daily sales summaries, monthly rollups, user activity aggregations—these change when new data arrives and are queried constantly.

ETL pipelines use materialized views as intermediate stores. Transform once, store the result, query it repeatedly.

When Materialized Views Don’t Help

Materialized views fail when:

  • Data changes frequently and you need current values
  • Query patterns are too diverse to precompute efficiently
  • Storage overhead exceeds the benefit
  • Refresh costs outweigh read savings

If the required refresh interval is shorter than the measured refresh time, a materialized view may not meet the freshness target. Consider a maintained summary table or an incremental data pipeline.

Materialized View Refresh Flows

flowchart TD
    subgraph FullRefresh["Full Refresh"]
        F1[("Materialized<br/>View")] -->|blocks reads| F2[("Drop + Recreate")]
        F2 --> F3[("New View<br/>Available")]
    end

    subgraph ConcurrentRefresh["Concurrent Refresh"]
        C1[("Old View<br/>Available")] --> C2[("Build index on<br/>new snapshot")]
        C2 --> C3[("Swap atomically<br/>when ready")]
        C3 --> C4[("Old view removed<br/>Reads continue")]
    end

    FullRefresh -.->|readers stay unblocked| ConcurrentRefresh

Full refresh blocks reads until complete. Concurrent refresh keeps the old view available while building the new one in the background.

When to Use / When Not to Use Materialized Views

Use materialized views when:

  • Underlying data changes infrequently compared to query frequency
  • Queries are expensive aggregations or multi-table joins
  • You can tolerate stale data for a known period
  • Query patterns are predictable and stable
  • You need to replicate remote data locally

Do not use materialized views when:

  • Data changes frequently and you need current values
  • Query patterns are too diverse to precompute efficiently
  • Storage overhead exceeds the benefit
  • Refresh costs outweigh read savings
  • You need real-time data accuracy

Materialized View vs Regular View vs Denormalization Trade-offs

Dimension Regular View Materialized View Denormalization
Storage None — query only Stores result as table Manual data duplication
Read performance Same as query Fast — reads precomputed Fast — reads precomputed
Freshness Always current Stale until refresh Manual — application manages
Write impact None Refresh blocks or takes time Updates more complex
Maintenance None Periodic refresh needed Application-level sync
Consistency Strong Depends on refresh frequency Application-dependent
Best for Hiding complexity, access control Precomputed aggregations, remote data Read-heavy workloads, specific shapes

Production Failure Scenarios

Failure Impact Mitigation
Full refresh blocking reads Queries fail during refresh window Use CONCURRENTLY option with unique index
Refresh lag causing stale reports Business decisions on outdated numbers Track the latest successful source watermark
Refresh competes with writes Resource use overlaps with write load Measure on the target workload and schedule around peaks
Unique index missing for concurrent refresh PostgreSQL refuses CONCURRENTLY Always create unique index before concurrent refresh
Materialized view growing too large More storage and potentially longer refreshes Limit the retained result or use a custom partitioned summary table
Index missing on frequently filtered columns Slow reads from materialized view Add indexes like any table — materialized views are tables

Estimate storage and refresh cost

A materialized view stores its result plus any indexes. Estimate row count and row width from representative data, then measure the relation and index sizes in a staging database. Query shape, data types, index fill, and database version all affect the result, so a hand-calculated byte count is only a rough planning aid.

Refresh duration is also workload-specific. Record elapsed time, rows produced, source-table activity, and read availability for each run. Compare full refresh and concurrent refresh in PostgreSQL with the actual query; PostgreSQL’s concurrent option reruns the defining query and is not an incremental refresh. For Oracle, test the eligible FAST method against the COMPLETE fallback using the deployed view definition and logs.

Observability Hooks: Monitoring Materialized View Health

PostgreSQL does not expose a last_refresh column in pg_matviews. Record refresh start, finish, status, and source watermark in the scheduler or an application-owned history table. For example:

CREATE TABLE mv_refresh_history (
    mv_name TEXT NOT NULL,
    refresh_started TIMESTAMPTZ NOT NULL,
    refresh_finished TIMESTAMPTZ,
    status TEXT NOT NULL,
    source_watermark TIMESTAMPTZ
);

Use the scheduler to write a row before refresh and update it on success or failure. Then calculate staleness from the latest successful source_watermark, not from a guessed catalog timestamp. Keep the refresh command and history update in the same job so missed runs are visible.

You can inspect materialized-view sizes with PostgreSQL’s relation-size functions:

SELECT
    schemaname,
    matviewname,
    pg_size_pretty(pg_total_relation_size(format('%I.%I', schemaname, matviewname)::regclass)) AS total_size
FROM pg_matviews
WHERE schemaname = 'public';

Set alerts from the freshness target agreed for the report: latest successful source watermark, refresh failures, elapsed refresh time, and unexpected result-size changes. A change in duration is a signal to investigate the query plan and input volume, not proof of a particular cause.

Interview Questions

1. What is the difference between REFRESH MATERIALIZED VIEW and REFRESH CONCURRENTLY?

A regular PostgreSQL refresh blocks reads of that materialized view while it runs. REFRESH MATERIALIZED VIEW CONCURRENTLY allows reads to continue, but requires a populated view and a qualifying unique index that uses only column names and includes all rows. It still evaluates the full defining query and reconciles the result; it is not incremental maintenance and does not use CREATE INDEX CONCURRENTLY semantics. Refresh duration and resource use depend on the query and data, so benchmark the real workload.

2. How do you keep a materialized view from growing unbounded?

Choose the retention window from the queries and reports that use the result, then encode that boundary in the view definition or source data lifecycle. PostgreSQL's built-in materialized-view refresh does not refresh only one partition. If you need partition-level retention or incremental maintenance, consider a custom partitioned summary table or pipeline and define how late-arriving and corrected records are handled.

3. A materialized view refresh is causing replication lag on your read replica. What do you do?

For physical replication, refresh the materialized view on the writable primary; the resulting database changes are applied by standbys through WAL replay. Measure WAL volume, standby apply lag, and refresh time on the actual workload instead of assuming a fixed amount of generated WAL. If the freshness target permits a slower schedule, use it; otherwise consider a separate reporting pipeline or a different replica architecture.

4. When would you choose a materialized view over denormalization managed in application code?

A materialized view stores a query result and follows the database product’s refresh rules. Application-managed denormalization lets the application update a custom read model, but the application must keep it consistent. Compare both against the required freshness, write path, failure recovery, and query shape.

5. How do you decide between REFRESH MATERIALIZED VIEW and REFRESH CONCURRENTLY in production?

Use a regular refresh when readers can be blocked and the measured refresh fits the maintenance window. Use REFRESH CONCURRENTLY when readers must continue querying the populated view and a qualifying unique index exists. Concurrent refresh does not guarantee zero downtime for the broader application, and it still reevaluates the defining query.

6. A materialized view is used for daily reports that must be accurate as of midnight. The refresh takes 2 hours. What do you do?

First define the report cutoff and maximum acceptable age. PostgreSQL materialized-view refresh reruns the query, including with CONCURRENTLY; it does not refresh one partition of the view. If that full query cannot meet the target, publish a partitioned summary table or use a pipeline that processes changed partitions. In Oracle, check fast-refresh eligibility and logs for the exact query, then test inserts, updates, and deletes before choosing FAST.

7. What is the difference between a materialized view and a materialized aggregate table?

“Materialized aggregate table” is not a separate PostgreSQL refresh feature. PostgreSQL materialized views store the result of a defining query, including aggregates, and `REFRESH MATERIALIZED VIEW` reruns that query. Oracle can use `FAST` refresh for eligible definitions with required logs; eligibility depends on the exact query, tables, and database version. Do not infer incremental maintenance from an aggregate being additive.

8. How do you monitor materialized view health in production? What metrics matter most?

Track the last successful refresh and source watermark in the scheduler or an application-owned table; pg_matviews does not provide a last-refresh timestamp. Monitor refresh failures, elapsed time, and result size against workload-specific baselines. Set the staleness alert from the report’s agreed freshness target.

9. You need to create a materialized view but the query takes 30 minutes. How do you handle initial population?

Choose `WITH DATA` when the initial query can run inside the deployment window. `WITH NO DATA` creates an unpopulated view; it cannot be queried until a successful refresh. PostgreSQL does not support inserting rows directly into a materialized view or refreshing only a partition. If initial population is too expensive, build a separate summary table or data pipeline with explicit batch and recovery behavior.

10. How does partitioning affect materialized view refresh performance?

PostgreSQL has no `REFRESH MATERIALIZED VIEW ... WHERE` syntax: its built-in refresh reruns the full definition. For incremental partition-level updates, maintain a custom summary table or pipeline that records changed partitions and applies changes idempotently, including updates, deletes, retries, and reconciliation. Oracle's fast-refresh and partition change tracking options have separate eligibility rules; check the Oracle Database 26ai refresh documentation for the chosen query and logs.

11. What happens to a materialized view when the underlying table is altered (column added, type changed)?

PostgreSQL does not automatically update the MV schema when the underlying table changes. If you add a column to the source table, the MV does not automatically include it — you must DROP and RECREATE the MV. If you change a column type, the MV may error on refresh if the new type is incompatible with the MV's query. The MV does not automatically detect schema drift. The mitigation: treat MV definitions as versioned code, include them in migration scripts, and always test MV refresh after schema changes. Some teams use automated migration scripts that detect MVs depending on a table and include their recreation in the migration plan.

12. When would you choose to use a regular view with indexing instead of a materialized view?

Use a regular view when: you need always-current data (materialized views are stale by definition), your query is not expensive enough to justify precomputation (sub-second response times are acceptable), or you query the view infrequently enough that the storage cost of materialization is not worth it. Use a regular view + index when: the underlying tables are small or the query is simple enough that the database handles it efficiently, or when query patterns are too diverse to precompute effectively. Materialized views trade freshness and storage for a precomputed result; a regular view runs its query when read. If your query is slow and data freshness matters less than performance, materialize. If data freshness matters more, index the underlying tables and use a regular view.

13. How do you handle materialized views in a multi-tenant SaaS database where each tenant needs isolated data?

A shared materialized view can include tenant_id in its result so queries can filter by tenant. PostgreSQL refresh still rebuilds the entire view; it cannot refresh one tenant with a predicate. Separate views can have separate schedules but add schema and operations overhead. Before choosing, compare row-level security, database permissions, refresh cost, and the failure behavior of any application-maintained read model.

14. Can you nest materialized views? Create an MV that is based on another MV?

Yes, you can create a materialized view on top of another materialized view in PostgreSQL. The dependent MV refreshes independently and does not automatically track the parent MV refresh. If MV A = SELECT * FROM table, and MV B = SELECT * FROM MV A, refreshing MV A does not refresh MV B — you must explicitly refresh MV B. This creates a dependency chain: refresh order matters. If MV B depends on MV A, always refresh MV A first. Some teams avoid nested MVs because the dependency chain becomes hard to manage. If you need layered precomputation (aggregating from raw fact to daily rollup to monthly summary), consider whether a single MV at the right aggregation level is simpler than nested MVs.

15. What is the relationship between materialized views and query caching? When would you choose one over the other?

Materialized views are precomputed and stored on disk — the result is the MV itself, ready to query at any time. Query caching (Redis, Memcached) stores query results in memory with a TTL. Materialized views persist across restarts; query cache does not. Choose materialized views when: the same query runs frequently across many users, the underlying data changes infrequently, and you need consistent results without TTL expiration variation. Choose query caching when: results need to be served in sub-millisecond time, you are okay with stale data up to TTL, or the query is too dynamic to precompute effectively. Use both: materialized view as the source of truth for consistency, query cache in front for microsecond serving of already-computed results.

16. How do you handle materialized view maintenance during database maintenance windows with zero downtime requirements?

In PostgreSQL, a populated view with a qualifying unique index can use REFRESH MATERIALIZED VIEW CONCURRENTLY so reads can continue during the refresh. Without that option, readers are blocked on the view. A replacement-view workflow may be possible for a particular schema, but renames, dependencies, grants, and application references need their own migration plan; do not assume an atomic swap is transparent. Test the exact DDL and reader behavior on the target PostgreSQL version.

17. How do you implement partition-aligned materialized view refresh in PostgreSQL when the source table is partitioned?

PostgreSQL's refresh command has no partition predicate; it reruns the full query even when its base table is partitioned. If only changed ranges should be maintained, use an application-managed summary table or pipeline and test inserts, updates, deletes, and late data. Oracle partition change tracking and fast refresh are different product features with their own eligibility requirements; they are not equivalent to a PostgreSQL refresh predicate.

18. What are the key differences between PostgreSQL materialized views and Oracle materialized views that affect your implementation choices?

Oracle Database 26ai supports on-demand refresh and, for eligible views, on-commit or fast refresh; query rewrite also depends on configuration and eligibility. PostgreSQL 18 refreshes materialized views with REFRESH MATERIALIZED VIEW, including its full-query CONCURRENTLY option, and does not provide built-in fast refresh or automatic query rewrite for materialized views. A scheduler such as pg_cron can run refresh commands, but scheduling and freshness policy are application or operations choices. Compare the exact view definition and workload against the product-version documentation before choosing.

19. What index strategies work best for materialized views? When should you index the MV differently from the underlying query?

Index the MV based on how it is queried, not how it was defined. If the MV sales_by_month(customer_id, month, total_sales) is always queried with WHERE month = '2025-01' and ORDER BY customer_id, create a composite index on (month, customer_id). The MV is a table — index it like any table based on access patterns. Common mistake: assuming the underlying query's indexes are enough. They are not because the MV is a separate table with its own data. For low-cardinality columns (status flags), bitmap indexes work well in Oracle but PostgreSQL only supports btree, hash, and gin. If your MV serves multiple query patterns, consider multiple indexes. For high-cardinality filtering, btree indexes are most effective.

20. How do you use materialized views as a data replication mechanism across multiple databases?

MVs as a replication mechanism: create an MV on database B that selects from a foreign table (Postgres Foreign Data Wrapper) or materialized view on database A that is updated periodically. The pattern: production database has normalized tables; reporting database has MVs that pull from production via FDW or CDC (Change Data Capture). The MV serves the reporting workload without touching production. For multi-region replication, each region has local MVs that refresh from the primary. This is not real-time — there is lag between refreshes. For near-real-time replication, use logical replication (PostgreSQL's built-in) or Debezium + Kafka instead of MVs. MVs work well for hourly/daily batch synchronization to a reporting database.


Further Reading

Official Documentation:

Performance and Optimization:

Architecture Patterns:


Conclusion

Materialized views store query results for later reads, so those results can be stale until refresh. PostgreSQL 18 reruns the defining query, including with CONCURRENTLY; Oracle Database 26ai offers additional refresh methods when the view is eligible.

They fit repeated queries whose users can accept the refresh schedule. If the data must be current or the query varies too much, a regular view or a separately maintained read model may fit better.


Category

Related Posts

Denormalization

When to intentionally duplicate data for read performance. Tradeoffs with normalization, update anomalies, and application-level denormalization strategies.

#database #denormalization #performance

Connection Pooling: HikariCP, pgBouncer, and ProxySQL

Learn connection pool sizing, HikariCP, pgBouncer, and ProxySQL, timeout settings, idle management, and when pooling helps or hurts performance.

#database #connection-pooling #performance

Database Monitoring: Metrics, Tools, and Alerting

Monitor PostgreSQL with user-facing latency, connection and lock pressure, replication lag, and disk headroom. Includes versioned system-view examples and alert guidance.

#database #monitoring #observability