# Topic 38: Views, Materialized Views & Zero-Downtime Refresh
Virtual views, updateable views, materialized physical caching, CONCURRENTLY refreshes, and security abstractions.
1. Definition
A View is a stored virtual query that does not store data physically. A Materialized View physically caches the query results on disk and can be indexed for high-performance reporting.
2. Explain Like I'm 5
A View is a saved bookmark or shortcut: every time you click it, the query runs fresh. A Materialized View is a downloaded PDF snapshot: it is instant to open, but needs to be refreshed periodically.
3. Animation & Visual Simulation
Interactive Engine TraceViews, Materialized Views & Zero-Downtime Refresh Visual Simulator
CREATE MATERIALIZED VIEW mv_user_summary AS
SELECT user_id, COUNT(*) AS orders, SUM(amount) AS spent
FROM orders
GROUP BY user_id;
CREATE UNIQUE INDEX idx_mv_user ON mv_user_summary(user_id);Active InputStep 1: Input & Parsing Stage
Initiating Views, Materialized Views & Zero-Downtime Refresh
Checking Table Invariants
The database engine inspects active tables, verifies permissions, and prepares the physical operation.
4. Real-World Example
An executive analytics dashboard querying complex joins across millions of orders.
| Feature | Standard View | Materialized View |
|---|---|---|
| Data Storage | Virtual (Runs query on call) | Physical disk storage (Cached) |
| Speed | Slow on heavy joins | Sub-millisecond index lookups |
| Freshness | 100% real-time | Requires REFRESH command |
| Indexable | No | Yes (B-Tree, GIN, etc.) |
5. SQL Syntax
ANSI SQL / PostgreSQL DialectCREATE OR REPLACE VIEW active_customers AS SELECT id, name, email FROM users WHERE status = 'active';
-- 1. Create materialized view physically on disk:
CREATE MATERIALIZED VIEW mv_daily_sales AS
SELECT DATE_TRUNC('day', created_at) AS sale_date, SUM(amount) AS total_revenue
FROM orders
GROUP BY sale_date;
-- 2. Create UNIQUE index (Mandatory for CONCURRENT refresh):
CREATE UNIQUE INDEX idx_mv_daily_sales_date ON mv_daily_sales(sale_date);
-- 3. Zero-downtime refresh without blocking readers:
REFRESH MATERIALIZED VIEW CONCURRENTLY mv_daily_sales;6. Important Rules & Behaviors
| Rule | Behavioral Explanation |
|---|---|
| Standard View Freshness | Virtual views execute their underlying query on every single invocation. |
| Unique Index for CONCURRENTLY | REFRESH MATERIALIZED VIEW CONCURRENTLY strictly requires a unique index on the materialized view. |
| Security Barrier | Views can restrict sensitive columns (e.g. hiding password_hash or credit card numbers) from specific roles. |
| View macro expansion | Standard views do not store data; the query planner expands the view definition into the outer query AST at compile time. |
| Concurrent refresh prerequisites | REFRESH MATERIALIZED VIEW CONCURRENTLY requires at least one UNIQUE index on the materialized view. |
7. Deep Dive: Zero-Downtime Cache Invalidation: REFRESH CONCURRENTLY
A standard REFRESH MATERIALIZED VIEW acquires an ACCESS EXCLUSIVE lock on the view, blocking all reads until refresh completes. Adding the CONCURRENTLY keyword creates a temporary copy, computes a diff, and applies changes in place with zero read downtime.
-- Production Zero-Downtime refresh job: REFRESH MATERIALIZED VIEW CONCURRENTLY mv_leaderboard;
8. Advantages & Disadvantages
Advantages
- •Standard views simplify query complexity and enforce column security.
- •Materialized views provide sub-millisecond speeds on multi-million row aggregations.
Disadvantages & Trade-offs
- •Materialized views require scheduled refresh jobs and can serve slightly stale data.
9. Common Interview Questions
Q1.What is the architectural difference between a Standard View and a Materialized View?
A Standard View is a virtual query rewrite macro: it stores ZERO data on disk. When queried, the engine expands the view SQL into the underlying query AST and executes it against the base tables. A Materialized View executes the query once and persists the physical result as an actual table on disk, consuming disk space but allowing direct B-Tree indexing and sub-millisecond reads.
| Feature | Standard View | Materialized View |
|---|---|---|
| Storage on Disk | 0 bytes (virtual query macro) | Full physical table heap on disk |
| Read Performance | Same as underlying query | Ultra-fast (point lookups on indexed disk pages) |
| Data Freshness | 100% real-time (instant) | Stale until REFRESH is executed |
| Direct Indexing | NOT supported | Fully supported (B-Tree, GIN, etc.) |
| Write Overhead | Zero write overhead on base tables | Requires periodic background refresh cost |
Q2.How does "REFRESH MATERIALIZED VIEW CONCURRENTLY" work in PostgreSQL?
A standard REFRESH acquires an AccessExclusiveLock, locking out all readers until the refresh completes. REFRESH ... CONCURRENTLY allows concurrent readers to continue reading the old data without locking! It creates a temporary table with the new data, compares differences using a UNIQUE index, and applies atomic row updates to the live view using an ExclusiveLock that allows readers.
Q3.What are Updatable Views and what restrictions apply to them?
An Updatable View allows clients to execute INSERT, UPDATE, or DELETE directly against the view. Under ANSI SQL, a view is automatically updatable only if: 1. It references exactly one base table in FROM, 2. It contains no GROUP BY, HAVING, DISTINCT, or aggregate functions, 3. It contains no window functions, and 4. All non-nullable table columns are included in the view.
Q4.What is the "WITH CHECK OPTION" clause on updatable views?
When a view filters rows (e.g. WHERE country = 'US'), an application could update a row setting country = 'UK', causing the row to disappear from the view. Specifying WITH CHECK OPTION instructs the engine to validate updates and inserts against the view’s WHERE clause, throwing an error if the modified row would no longer satisfy the view definition.
Q5.How do you implement incremental real-time materialized views in PostgreSQL without extensions?
PostgreSQL does not natively support automatic incremental materialized view refresh. In production, teams either: 1. Schedule a cron job executing REFRESH CONCURRENTLY every 5 minutes, 2. Create an ordinary summary table and maintain it in real-time using AFTER INSERT/UPDATE/DELETE triggers on base tables, or 3. Use specialized streaming database engines like Materialize or ClickHouse.
10. Interview-Ready Answer
“Views are virtual query shortcuts providing security and abstraction. Materialized views physically persist and index complex aggregation results on disk, with REFRESH MATERIALIZED VIEW CONCURRENTLY providing non-blocking zero-downtime cache updates.”
11. Quick Test
What is strictly required on a Materialized View before you can execute REFRESH MATERIALIZED VIEW CONCURRENTLY?