Date and time types in MySQL - Time & Space Complexity
When working with date and time types in MySQL, it's important to understand how operations on these types behave as data grows.
We want to know how the time to process date and time values changes when the amount of data increases.
Analyze the time complexity of the following query that filters rows by a date range.
SELECT *
FROM orders
WHERE order_date BETWEEN '2023-01-01' AND '2023-12-31';
This query selects all orders placed within the year 2023 by checking the order_date column.
Look at what repeats as the query runs:
- Primary operation: Checking each row's order_date to see if it falls in the given range.
- How many times: Once for every row in the orders table.
As the number of orders grows, the database checks more dates.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 date checks |
| 100 | 100 date checks |
| 1000 | 1000 date checks |
Pattern observation: The number of checks grows directly with the number of rows.
Time Complexity: O(n)
This means the time to run the query grows in a straight line as the number of rows increases.
[X] Wrong: "Date and time checks are instant and don't depend on data size."
[OK] Correct: Each row's date must be checked, so more rows mean more work.
Understanding how date and time filtering scales helps you explain query performance clearly and confidently.
"What if we add an index on the order_date column? How would the time complexity change?"