NOW, CURDATE, CURTIME in MySQL - Time & Space Complexity
We want to understand how the time it takes to get the current date and time changes as we ask more times.
How does the cost grow when using NOW, CURDATE, and CURTIME functions repeatedly?
Analyze the time complexity of the following code snippet.
SELECT NOW();
SELECT CURDATE();
SELECT CURTIME();
-- Using these functions in a query with many rows
SELECT id, NOW() FROM orders;
This code gets the current date and time, date only, or time only. It also shows using NOW() for each row in a table.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Calling NOW(), CURDATE(), or CURTIME() functions.
- How many times: Once if called alone; once per row if used in a query with many rows.
Getting the current time once is very fast and does not depend on input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 calls if used per row |
| 100 | 100 calls if used per row |
| 1000 | 1000 calls if used per row |
Pattern observation: The total work grows linearly with the number of rows when used per row.
Time Complexity: O(n)
This means the time to get the current time grows directly with the number of rows you ask for.
[X] Wrong: "Calling NOW() once in a query with many rows only runs once and is very cheap."
[OK] Correct: In many SQL engines, NOW() is evaluated once per row, so the cost grows with rows, not constant.
Understanding how functions like NOW() behave with many rows helps you write efficient queries and shows you think about performance.
"What if we used NOW() in a WHERE clause instead of SELECT? How would the time complexity change?"