I want to select all records from a table Log
where the DateAndTime
field values (of type datetime
) are for the day before today, whatever day it is.
So if today is 2011-06-08, I want to select all rows where DateAndTime
is greater than or equal to 2011-06-07 00:00:00
and also less than 2011-06-08 00:00:00
.
I'm guessing the potential pitfall here would be it's behaviour on the 1st day of the month, as obviously a date like 2011-06-00
is invalid, and should be 2011-05-31
.
To get yesterday's date, you need to subtract one day from today's date. Use GETDATE() to get today's date (the type is datetime ) and cast it to date . In SQL Server, you can subtract or add any number of days using the DATEADD() function. The DATEADD() function takes three arguments: datepart , number , and date .
SELECT * FROM product WHERE pdate >= DATEADD(day, -30, getdate()).
Here's the SQL query to get records from last 7 days in MySQL. In the above query we select those records where order_date falls after a past interval of 7 days. We use system function now() to get the latest datetime value, and INTERVAL clause to calculate a date 7 days in the past.
In SQL Server, you can use the DATEADD() function to get last 3 months (or n months) records.
For SQL Server 2008 you can use this.
select *
from [log]
where cast(DateAndTime as date) = cast(getdate()-1 as date)
Pre 2008 you can use this
select *
from [log]
where DateAndTime >= dateadd(d, datediff(d, 0, getdate())-1, 0) and
DateAndTime < dateadd(d, datediff(d, 0, getdate()), 0)
Related on DBA: Cast to date is sargable but is it a good idea?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With