SQL Select Records based on current date minus two days SQL Select Records based on current date minus two days sql-server sql-server

SQL Select Records based on current date minus two days


you should try to use dateadd function

select * from orders where orderdate > dateadd(dd,-1,cast(getdate() as date))

Now this may exactly what you need but then you need to understand that by casting to date we remove the time part and effectively going back to start of the day and a day behind it(-1) gives the start of yesterday.


Try this:

select * from orders where orderdate > cast(getdate() - 1 as date)


If you want the orders of the last two days, use DATEADD to add days to today's date (in your case -2 days) then use DATEDIFF to compare the two days:

SELECT * FROM ordersWHERE DATEDIFF(DAY, DATEADD(DAY, -2, GETDATE()), orderdate) > 0

Now, assuming all orders have dates in the past and none in the future (which is what it should be), you can simply use DATEDIFF like this:

SELECT * FROM ordersWHERE DATEDIFF(DAY, orderdate, GETDATE()) <= 2

Note: you can use < 3 instead of <= 2.