Materialized views concept in PostgreSQL - Time & Space Complexity
Materialized views store query results to speed up repeated access.
We want to know how the time to refresh a materialized view grows as data grows.
Analyze the time complexity of refreshing a materialized view.
CREATE MATERIALIZED VIEW sales_summary AS
SELECT product_id, SUM(quantity) AS total_quantity
FROM sales
GROUP BY product_id;
REFRESH MATERIALIZED VIEW sales_summary;
This code creates a materialized view summarizing sales by product and refreshes it.
Look for repeated work done during refresh.
- Primary operation: Scanning all rows in the sales table to aggregate quantities.
- How many times: Once per refresh, processing every sales record.
The refresh reads all sales rows to compute sums.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 row reads and sums |
| 100 | About 100 row reads and sums |
| 1000 | About 1000 row reads and sums |
Pattern observation: Operations grow roughly in direct proportion to the number of rows.
Time Complexity: O(n)
This means refreshing takes time proportional to the number of rows in the base table.
[X] Wrong: "Refreshing a materialized view is instant no matter the data size."
[OK] Correct: The refresh must read and process all underlying data, so it takes longer as data grows.
Understanding how materialized views refresh helps you explain database performance in real projects.
"What if we added an index on product_id? How would that affect the refresh time complexity?"