TSQL SELECT previous date's records

40,936

Solution 1

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?

Solution 2

SELECT * FROM Log
WHERE DateAndTime >= DATEADD(DAY,-1, CAST(GETDATE() AS DATE))
AND DateAndTime < CAST(CAST(GETDATE() AS DATE) AS DATETIME)

Solution 3

This example assumes SQL Server:

select *
from log
where convert(varchar(8), DateAndTime , 112)  = convert(varchar(8), getdate()-1, 112)

Essentially, convert the date to yyyymmdd (the 112 parameter) and then check it is equal to yesterday's date (getdate()-1), also converted to yyyymmdd.

Share:
40,936

Related videos on Youtube

Alex
Author by

Alex

I first started building websites when I was about 11, and I like to think that I have improved somewhat. From there I got interested in programming and databases and all that exciting stuff. I'm a big fan of PHP, but I'm also interested in other languages. I've recently been messing about with binary files a lot in PHP, so I'm wondering about trying my hand at a strongly-typed language like C++, C or Java. Outside of computing, my other interests include riding my bike, skateboarding, reading, and space :)

Updated on September 20, 2020

Comments

  • Alex
    Alex over 3 years

    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.

  • Adriaan Davel
    Adriaan Davel over 9 years
    Casting the column could have serious performance implications, see JanW's solution below
  • Mikael Eriksson
    Mikael Eriksson over 9 years
    @AdriaanDavel Yes it can, with cardinality estimates. Not with sargability. Did you read the question on DBA linked from my answer?