Views & Materialized Views: Mistakes
Module: Schema Design & Advanced DDL
Using regular views expecting performance improvement
Use materialized views for performance, regular views for security/abstraction
Regular views don't cache results. They execute the underlying query every time. If the query is slow, the view is slow. Use materialized views to pre-compute and store results for fast queries.
High
graph TD
A[Regular View] --> B[Executes query every time]
B --> C[No performance benefit]
D[Materialized View] --> E[Stores pre-computed results]
E --> F[Fast queries]
style C fill:#FFB6C6
style F fill:#90EE90
Forgetting to refresh materialized views
Schedule automatic refresh with pg_cron or application scheduler
Materialized views don't update automatically. Data becomes stale. Users see outdated information. Solution: Schedule automatic refresh (hourly, daily) or refresh on-demand after data changes.
Critical
sequenceDiagram
participant Data
participant MV
participant Users
Data->>Data: Changes accumulate
Note over MV: Stale data
Users->>MV: Query
MV-->>Users: Outdated results
Note over MV: Need REFRESH!
Not indexing materialized views
Create indexes on materialized views just like regular tables
Materialized views are tables. Without indexes, queries do full table scans. Slow. Solution: CREATE INDEX on commonly filtered/sorted columns. Treat materialized views like regular tables for indexing.
High