Recently I read a long article about the difference between SYSDATE() and CURRENT_DATE() in Oracle databases. It reminded me that I once researched the difference between NOW() and SYSDATE() in MySQL. These functions seem very similar, and for many (most?) uses, you’d be hard-pressed to observe a difference. But they’re not exactly the same. Here’s a quick guide on which to use when.
The simpler of the two, and probably what you expect, is SYSDATE(). SYSDATE() returns the timestamp (not just the date) of the exact instant when it operates.
MariaDB [(none)]> select sysdate(); +---------------------+ | sysdate() | +---------------------+ | 2024-01-27 18:09:04 | +---------------------+
Simple enough. Now (no pun intended!) let’s compare NOW() and SYSDATE():
MariaDB [(none)]> select now(), sysdate(); +---------------------+---------------------+ | now() | sysdate() | +---------------------+---------------------+ | 2024-01-27 18:09:50 | 2024-01-27 18:09:50 | +---------------------+---------------------+
Hmmm…they’re the same?!?
Here’s something that will illustrate the difference:
MariaDB [(none)]> select now(), sleep(10), sysdate(); +---------------------+-----------+---------------------+ | now() | sleep(10) | sysdate() | +---------------------+-----------+---------------------+ | 2024-01-27 18:11:12 | 0 | 2024-01-27 18:11:22 | +---------------------+-----------+---------------------+
Here’s the difference: NOW() is the time the query started. If it’s in a trigger or a stored procedure, it’s the time the code started executing. SYSDATE() always returns the time the instant it’s executed.
Why would you want NOW()? Let’s imagine you’re processing a huge table (millions of rows) and want to select all records that are 24 hours or older. You could do something like this:
SELECT record_id FROM big_table WHERE date_entered < NOW() - INTERVAL 1 DAY;
NOW() is going to execute once at the beginning of that query and use the value it gets for every row comparison. However, if you change that code to SYSDATE() it’s going to run a lot slower because it’ll execute SYSDATE() for each and every row. Not only is that a ton of processing, it also can give you an inconsistent answer because what was 24 hours old for row 1 may be different for row 10,000,000.
For small datasets, quick queries, etc. these things may not come into play, and perhaps in your code it doesn’t really matter if you’ve got that much prevision. But at scale, you should be aware of the differences.
BTW, MySQL and MariaDB both offer you the option to make SYSDATE() behave exactly as NOW() should you wish.
Related Posts:
- Crunchbits Discontinuing Popular Annual Plans – The Community Mourns! - November 20, 2024
- RackNerd’s Black Friday 2024: Bigger, Better, and Now in Dublin! - November 19, 2024
- It’s the Season of Giving and CharityHost Has Deals for You! - November 18, 2024
Leave a Reply