Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying datetime columns for 'Now' minus a certain amount of time?

Is there a way in TSQL to query for rows where a datetime column's value is "now minus (a certain amount of time)" to select a time range?

For example in MySQL I could build this predicate like:

(EndTime BETWEEN NOW() - INTERVAL 2 DAY AND NOW())

How can this be done in TSQL in SQL Server?

like image 545
Kyle Brandt Avatar asked Mar 29 '11 19:03

Kyle Brandt


2 Answers

You would use the dateadd function, e.g.

where endtime between dateadd(day, -2, getdate()) and getdate()

Because the column endtime is not a function parameter, the query optimizer can use any indexes that might be defined on it (the definition of sargable).

like image 195
Bobby D Avatar answered Sep 20 '22 17:09

Bobby D


If you are trying to subtract two days from today, you can do

DateAdd( d, -2, CURRENT_TIMESTAMP)

DATEADD (Transact-SQL)

like image 24
Thomas Avatar answered Sep 20 '22 17:09

Thomas