Search code examples
sqlsql-servert-sqlgetdate

Query data from previous day when month/year changes


In a SQL Server query, I am currently using the clause

WHERE
    DAY(trade_date) = DAY(GETDATE()) - 1 
    AND MONTH(trade_date) = MONTH(GETDATE()) 
    AND YEAR(trade_date) = YEAR(GETDATE())

to query my data from the previous day.

It is working fine right now but my question is if, for example, on 8/1/2021, SQL Server will try to get data from 8/0/2021 or if it will know to get data from 7/31/2021.

If this query won't work what could I use instead? Thanks!


Solution

  • I would recommend using proper date comparison logic - instead of breaking it down to day, month and year. Also, it is recommended to use proper date arithmetic functions like DATEADD instead of just - 1 on your date values (never sure what that -1 stands for: minus one day? Week? Month? Hour?).

    And lastly - I would also recommend using SYSDATETIME() instead of GETDATE() since the latter always returns a DATETIME datatype - which should be on its way out, and you should use DATE (if you don't need to time portion), or DATETIME2(n) (if you do need the time portion) since those are more efficient and have fewer limitations compared to DATETIME.

    If your trade_date is a DATE column (as it probably should be), just use:

    WHERE
        trade_date = DATEADD(DAY, -1, SYSDATETIME())
    

    and if it's not a DATE - just cast it to a date as needed:

    WHERE
        CAST(trade_date AS DATE) = DATEADD(DAY, -1, CAST(SYSDATETIME() AS DATE))