REFRESH MATERIALIZED VIEW in PostgreSQL - Time & Space Complexity
When we refresh a materialized view, we update its stored data to match the current state of the original tables.
We want to understand how the time it takes to refresh grows as the data size increases.
Analyze the time complexity of the following PostgreSQL command.
REFRESH MATERIALIZED VIEW my_view;
This command rebuilds the materialized view by re-running its underlying query and storing fresh results.
Inside the refresh, the database runs the view's query, which usually scans tables and joins data.
- Primary operation: Scanning and processing all rows from the source tables involved in the view.
- How many times: Once per refresh, but the work depends on the total rows in the source tables.
As the number of rows in the source tables grows, the refresh takes longer because it must process more data.
| Input Size (n rows) | Approx. Operations |
|---|---|
| 10 | Processes about 10 rows |
| 100 | Processes about 100 rows |
| 1000 | Processes about 1000 rows |
Pattern observation: The work grows roughly in direct proportion to the number of rows.
Time Complexity: O(n)
This means the time to refresh grows linearly with the size of the data being processed.
[X] Wrong: "Refreshing a materialized view is always very fast regardless of data size."
[OK] Correct: The refresh must re-run the query and process all relevant rows, so larger data means more work and longer time.
Understanding how refreshing materialized views scales helps you explain database performance and design choices clearly.
"What if the materialized view used incremental refresh instead of full refresh? How would the time complexity change?"