Search code examples
sql-serversql-server-2014

How to select between, for example, between 6:15 and 7:15? Microsoft SQL Server 2014


I want to query data that happened between 6:15 and 7:15, 7:15:01 and 8:15 and so forth. So far I am only able to do the following:

Select *
From table
Where datepart(hh, t_stamp) = 7  
  and datepart(day, t_stamp) = day(getdate())

I am selecting all data that happens between 7:00 and 7:59:59....

I tried googling it. Found something using unix_timestamp, but that does not work in Microsoft SQL Server. I've been wrecking my brain but as a SQL noob (I am used to "ladder logic" in PLC programming) this is way out of my comfort zone.


Solution

  • If you are looking for fetching the data between a specific time, let's say 06:15 to 07:15 for any date, then convert the datetime to time and use it in the where clause.

    Query

    select * from your_table_name
    where cast(t_stamp as time) between '06:15:00' and '07:15:00';
    

    If you need it only for today's date, then add that condition too in the Where clause.

    select * from your_table_name
    where cast(t_stamp as time) between '06:15:00' and '07:15:00'
    and cast(t_stamp as date) = cast(getdate() as date);