CREATE MATERIALIZED VIEW in PostgreSQL - Time & Space Complexity
When we create a materialized view, the database runs a query and saves the results. Understanding how long this takes helps us plan for bigger data.
We want to know how the time to create the view changes as the data grows.
Analyze the time complexity of the following code snippet.
CREATE MATERIALIZED VIEW recent_orders AS
SELECT order_id, customer_id, order_date
FROM orders
WHERE order_date > CURRENT_DATE - INTERVAL '30 days';
This code creates a materialized view that stores orders from the last 30 days.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning the
orderstable to find rows matching the date condition. - How many times: Once for each row in the
orderstable.
The time to create the materialized view grows as the number of rows in orders grows, because each row must be checked.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 row checks |
| 100 | About 100 row checks |
| 1000 | About 1000 row checks |
Pattern observation: The work grows directly with the number of rows; doubling rows roughly doubles the work.
Time Complexity: O(n)
This means the time to create the materialized view grows in a straight line with the number of rows in the source table.
[X] Wrong: "Creating a materialized view is instant no matter how big the table is."
[OK] Correct: The database must read and store all matching rows, so bigger tables take more time.
Knowing how query time grows with data size helps you design efficient database features and explain your choices clearly.
"What if we added an index on order_date? How would the time complexity change when creating the materialized view?"