Creating views in MySQL - Performance & Efficiency
When we create a view in MySQL, it acts like a saved query. Understanding how long it takes to run this query matters.
We want to know how the time to get results grows as the data grows.
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);
This code creates a view showing orders from the last 30 days.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Scanning the orders table to find rows matching the date condition.
- How many times: Once for each row in the orders table when the view is queried.
As the number of orders grows, the database checks more rows to find recent ones.
| 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 roughly in direct proportion to the number of rows.
Time Complexity: O(n)
This means the time to get results grows linearly with the number of rows in the orders table.
[X] Wrong: "Creating a view makes the query run faster because it is saved."
[OK] Correct: The view just stores the query, but the database still runs it each time you ask for data, so the time depends on the data size.
Knowing how views work helps you explain query performance clearly and shows you understand how databases handle saved queries.
"What if we add an index on the order_date column? How would the time complexity change?"