Materialized view vs regular view decision in PostgreSQL - Performance Comparison
When choosing between a materialized view and a regular view, it's important to understand how their execution time changes as data grows.
We want to know how query speed behaves with each option as the database gets bigger.
Analyze the time complexity of querying a regular view versus a materialized view.
-- Regular view definition
CREATE VIEW sales_summary AS
SELECT product_id, SUM(quantity) AS total_quantity
FROM sales
GROUP BY product_id;
-- Materialized view definition
CREATE MATERIALIZED VIEW sales_summary_mat AS
SELECT product_id, SUM(quantity) AS total_quantity
FROM sales
GROUP BY product_id;
-- Querying the views
SELECT * FROM sales_summary;
SELECT * FROM sales_summary_mat;
The regular view runs the aggregation each time it is queried, while the materialized view stores the result and returns it directly.
Look at what happens when you query each view.
- Primary operation: Scanning and grouping the entire sales table.
- How many times: For the regular view, this happens every query; for the materialized view, it happens only when refreshed.
As the sales table grows, the time to compute the aggregation grows too.
| Input Size (n rows) | Regular View Query Time | Materialized View Query Time |
|---|---|---|
| 10 | Small, quick scan | Almost instant (precomputed) |
| 1000 | Longer scan and group | Still almost instant |
| 1000000 | Much longer scan and group | Still almost instant |
Pattern observation: Regular view query time grows roughly with data size; materialized view query time stays nearly constant.
Time Complexity: O(n) for regular view queries, O(1) for materialized view queries
This means regular views take longer as data grows, while materialized views return results quickly because they store precomputed data.
[X] Wrong: "Materialized views always speed up queries without any extra cost."
[OK] Correct: Materialized views need to be refreshed to update data, which can take time and resources, so they are not always the best choice for frequently changing data.
Understanding when to use materialized views versus regular views shows you can balance query speed and data freshness, a key skill in real database work.
"What if the materialized view is refreshed automatically after every insert? How would that affect the time complexity of queries and updates?"