Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL SELECT previous date's records

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.

like image 200
Alex Avatar asked Jun 08 '11 13:06

Alex


People also ask

How do I get previous day records in SQL?

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 .

How do I get last 30 days records in SQL?

SELECT * FROM product WHERE pdate >= DATEADD(day, -30, getdate()).

How do I get last 7 days record in SQL?

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.

How can I get last 3 months data in SQL?

In SQL Server, you can use the DATEADD() function to get last 3 months (or n months) records.


1 Answers

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?

like image 63
Mikael Eriksson Avatar answered Oct 14 '22 01:10

Mikael Eriksson