Is there a way to use the Now()
function in SQL to select values with today's date?
I was under the impression Now()
would contain the time as well as date, but today's date would have the time set to 00:00:00
and therefore this would never match?
OK, lets do this properly. Select dates matching today, using indexes if available, with all the different date/time types present.
The principle here is the same in each case. We grab rows where the date column is on or after the most recent midnight (today's date with time 00:00:00), and before the next midnight (tomorrow's date with time 00:00:00, but excluding anything with that exact value).
For pure date types, we can do a simple comparison with today's date.
To keep things nice and fast, we're explicitly avoiding doing any manipulation on the dates stored in the DB (the LHS of the
where
clause in all the examples below). This would potentially trigger a full table scan as the date would have to be computed for every comparison. (This behaviour appears to vary by DBMS, YMMV).MS SQL Server: (SQL Fiddle | db<>fiddle)
First, using DATE
Now with DATETIME:
Lastly with DATETIME2:
MySQL: (SQL Fiddle | db<>fiddle)
Using DATE:
Using DATETIME:
PostgreSQL: (SQL Fiddle | db<>fiddle)
Using DATE:
Using TIMESTAMP WITHOUT TIME ZONE:
Oracle: (SQL Fiddle)
Using DATE:
Using TIMESTAMP:
SQLite: (SQL Fiddle)
Using date strings:
Using date and time strings:
Using unix timestamps:
Backup of SQL Fiddle code
Not sure exactly what you're trying to do, but it sounds like
GETDATE()
is what you're after.GETDATE()
returns a datetime, but if you're not interested in the time component then you can cast to a date.You can try this sql code;
Just zero off the time element of the date. e.g.
I've used GetDate as that's an MSSQL function, as you've tagged, but Now() is probably MySQL or you're using the ODBC function call, still should work if you just replace one with the other.
If you have a table with just a stored date (no time) and want to get those by "now", then you can do this:
This results in rows which day difference is 0 (so today).
Not sure what your asking!
However
Will get you the current date and time
Will get you just the date with time set to 00:00:00