Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL (date) - how to get value within one hour?

I am looking for an optimal decision of how to get table values according to their date and time but within just ONE past hour.

I mean something in this way (a pseudocode):

 SELECT value FROM Table WHERE date BETWEEN getdate() AND getdate()-ONE_HOUR

For the purpose of this question Table has these columns:

  • value
  • date

Any useful snippet is appreciated :)

like image 306
user592704 Avatar asked Sep 28 '11 19:09

user592704


People also ask

How do I add 1 hour to a date in SQL?

How to add Hours to DateTime in Sql Server? We can use DATEADD() function like below to add hours to DateTime in Sql Server. DATEADD() functions first parameter value can be hour or hh all will return the same result.

How do I select hours from a date in SQL?

We can use DATEPART() function to get the HOUR part of the DateTime in Sql Server, here we need to specify datepart parameter of the DATEPART function as hour or hh.


2 Answers

SELECT Value
FROM Table
WHERE Date between dateadd(hour, -1, getdate()) and getdate()

Description of the DATEADD function:

DATEADD (datepart , number , date )

Returns a specified date with the specified number interval (signed integer) added to a specified datepart of that date.

datepart     Abbreviations  
-----------  -------------
year         yy, yyyy
quarter      qq, q
month        mm, m
dayofyear    dy, y
day          dd, d
week         wk, ww
weekday      dw, w
hour         hh 
minute       mi, n
second       ss, s
millisecond  ms 
microsecond  mcs 
nanosecond   ns 

More information:

  • DATEADD (Transact-SQL)
like image 194
The Evil Greebo Avatar answered Oct 14 '22 03:10

The Evil Greebo


Something like this should work.

SELECT value
FROM Table 
WHERE date >= dateadd(hour,-1,getdate())
   and date <= getdate()
like image 33
Gabe Avatar answered Oct 14 '22 04:10

Gabe