Querying from views in MySQL - Time & Space Complexity
When we query data from a view in MySQL, it's important to understand how the time to get results grows as the data grows.
We want to know how the query's work changes when the underlying tables get bigger.
Analyze the time complexity of the following code snippet.
CREATE VIEW recent_orders AS
SELECT order_id, customer_id, order_date
FROM orders
WHERE order_date >= DATE_SUB(CURDATE(), INTERVAL 30 DAY);
SELECT * FROM recent_orders WHERE customer_id = 123;
This code creates a view showing orders from the last 30 days, then queries that view for a specific customer's orders.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning the orders table rows that match the date condition.
- How many times: Once for each row in the orders table within the last 30 days.
As the number of recent orders grows, the query must check more rows to find those for the specific customer.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 rows scanned |
| 100 | About 100 rows scanned |
| 1000 | About 1000 rows scanned |
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 rows in the view.
[X] Wrong: "Querying a view is always faster than querying the table directly because it's pre-made."
[OK] Correct: A view is just a saved query. It runs fresh each time, so its speed depends on the underlying tables and filters.
Understanding how views affect query time helps you explain real database behavior clearly and confidently.
"What if the view included a join with another large table? How would that change the time complexity?"