View as a saved query mental model in SQL - Time & Space Complexity
When we use a view in SQL, it acts like a saved query. Understanding how long it takes to run helps us know how it affects our database.
We want to see how the time to get results grows as the data gets bigger.
Analyze the time complexity of the following SQL view and query.
CREATE VIEW RecentOrders AS
SELECT OrderID, CustomerID, OrderDate
FROM Orders
WHERE OrderDate >= DATE_SUB(CURDATE(), INTERVAL 30 DAY);
SELECT * FROM RecentOrders WHERE CustomerID = 12345;
This view saves a query that finds orders from the last 30 days. Then we select orders for one customer from that view.
Look at what repeats when running the query.
- Primary operation: Scanning orders from the last 30 days.
- How many times: Once per query execution, scanning all recent orders.
As the number of recent orders grows, the work to find matching customer orders grows too.
| Input Size (n recent orders) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The work grows roughly in direct proportion to the number of recent orders.
Time Complexity: O(n)
This means the time to get results grows linearly with the number of recent orders.
[X] Wrong: "Using a view makes the query run instantly, no matter how much data there is."
[OK] Correct: A view is just a saved query. The database still runs the query each time, so bigger data means more work.
Understanding how views work and their time cost shows you know how databases handle saved queries, a useful skill for real projects.
"What if we added an index on CustomerID in the Orders table? How would the time complexity change?"