I am trying to select only today's records from a database table.
Currently I use
SELECT * FROM `table` WHERE (`timestamp` > DATE_SUB(now(), INTERVAL 1 DAY));
But this takes results for the last 24 hours, and I need it to only select results from today, ignoring the time. How can I select results based on the date only ?
use
DATE
andCURDATE()
I guess using
DATE
still uses INDEX.see the execution plan on the DEMO
On Visual Studio 2017, using the built-in database for development I had problems with the current given solution, I had to change the code to make it work because it threw the error that DATE() was not a built in function.
Here is my solution:
where CAST(TimeCalled AS DATE) = CAST(GETDATE() AS DATE)
If you want an index to be used and the query not to do a table scan:
To show the difference that this makes on the actual execution plans, we'll test with an SQL-Fiddle (an extremely helpful site):
Lets try the 2 versions now.
Version 1 with
DATE(timestamp) = ?
Explain:
It filters all (6671) rows and then does a filesort (that's not a problem as the returned rows are few)
Version 2 with
timestamp <= ? AND timestamp < ?
Explain:
It uses a range scan on the index, and then reads only the corresponding rows from the table.
This could be the easiest in my opinion:
Simply cast it to a date:
How many ways can we skin this cat? Here is yet another variant.
SELECT * FROM
table
WHERE DATE(FROM_UNIXTIME(timestamp
)) = '2015-11-18';