DATE_ADD and DATE_SUB in MySQL - Time & Space Complexity
When using DATE_ADD and DATE_SUB in MySQL, it's helpful to know how the time to run these functions changes as the amount of data grows.
We want to see how the work done grows when we apply these date functions to many rows.
Analyze the time complexity of the following code snippet.
SELECT order_id, order_date,
DATE_ADD(order_date, INTERVAL 7 DAY) AS delivery_date
FROM orders;
This query adds 7 days to the order_date for each order to find the delivery date.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Applying DATE_ADD to each row's order_date.
- How many times: Once for every row in the orders table.
Each row requires one date addition operation, so the total work grows directly with the number of rows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 date additions |
| 100 | 100 date additions |
| 1000 | 1000 date additions |
Pattern observation: The work increases in a straight line as the number of rows increases.
Time Complexity: O(n)
This means the time to run the query grows directly in proportion to the number of rows processed.
[X] Wrong: "DATE_ADD runs in constant time no matter how many rows there are."
[OK] Correct: The function runs once per row, so more rows mean more total work.
Understanding how simple functions like DATE_ADD scale with data size helps you explain query performance clearly and confidently.
"What if we added a JOIN that doubles the number of rows? How would the time complexity change?"