DATE arithmetic (DATEDIFF, DATE_ADD) in SQL - Time & Space Complexity
When working with dates in SQL, we often calculate differences or add days. Understanding how the time it takes to do this grows with data size helps us write better queries.
We want to know: how does the work grow when we do date calculations on many rows?
Analyze the time complexity of the following code snippet.
SELECT employee_id,
DATEDIFF(day, hire_date, GETDATE()) AS days_worked,
DATEADD(day, 30, hire_date) AS trial_end_date
FROM employees;
This query calculates how many days each employee has worked and finds a date 30 days after their hire date.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The database processes each row in the employees table once.
- How many times: Once per employee record, so as many times as there are rows.
Each row requires a fixed amount of work to calculate date differences and add days.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 date calculations |
| 100 | 100 date calculations |
| 1000 | 1000 date calculations |
Pattern observation: The work grows directly with the number of rows. Double the rows, double the calculations.
Time Complexity: O(n)
This means the time to run the query grows in a straight line with the number of rows processed.
[X] Wrong: "Date calculations like DATEDIFF or DATEADD take the same time no matter how many rows there are."
[OK] Correct: Each row needs its own calculation, so more rows mean more work and longer time.
Knowing how date functions scale helps you explain query performance clearly and shows you understand how databases handle data row by row.
"What if we added a WHERE clause to filter only recent hires? How would that affect the time complexity?"