Views & Materialized Views: Concept
Module: Schema Design & Advanced DDL
A view is a saved SELECT query that looks like a table. When you query a view, the database executes the underlying query and returns results. No data is stored.
A materialized view is a saved SELECT query whose results are stored on disk. When you query it, you're reading pre-computed data. Fast queries, but data might be stale.
Think of it this way:
- Regular view = bookmark to a query (executes every time)
- Materialized view = screenshot of query results (fast but might be outdated)
Views are virtual tables that store queries, not data. Materialized views store actual query results on disk.
Use regular views for security (hide columns), abstraction (simplify complex queries), and backward compatibility (maintain old schema interface).
Use materialized views for expensive aggregations, complex joins, and reporting where data can be stale.
Refresh strategies: manual (REFRESH MATERIALIZED VIEW), scheduled (pg_cron), or incremental (track changes). Use CONCURRENTLY to avoid blocking queries during refresh.
Index materialized views like regular tables for best performance.
Every company with complex reporting uses materialized views. They're the standard solution for expensive analytics queries that don't need real-time data.
Regular views are everywhere too - they're how you implement row-level security, hide implementation details, and provide stable APIs over changing schemas.
In interviews, understanding the trade-offs shows you know production systems. Junior developers think views are just "saved queries." Senior engineers know when to use regular views (security, abstraction) vs materialized views (performance) vs denormalization (real-time performance).
You have a dashboard showing daily sales metrics. The query joins 5 tables, aggregates 10 million rows, and takes 45 seconds. Users refresh the dashboard 500 times per day. That's 6.25 hours of query time daily.
Option 1: Regular view - Still takes 45 seconds every time. No improvement.
Option 2: Materialized view - Pre-compute results, refresh hourly. Query takes 10ms. Dashboard loads instantly. Users are happy.
This is what materialized views do: they trade storage and refresh overhead for query speed. Netflix uses materialized views for "Top 10 in your country" - refreshed every 6 hours, queried billions of times. Reddit uses them for subreddit statistics - refreshed every 15 minutes, displayed on every page.
Regular views are different. They don't store data - they're saved queries. You use them for security (hide sensitive columns), abstraction (simplify complex joins), or convenience (reusable query logic). A view that shows "active_users" (WHERE status = 'active') is always current because it queries the base table every time.