Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a time is between two times (time DataType)

Tags:

I have a table that has a column "Created" as a datetime.

I'm trying to query to check if the time for the Created value is between two times.

The Created datetime for the first row is '2013-07-01 00:00:00.000' (Midnight) and I'm trying to query for items with a time between 11PM and 7AM.

select * from MyTable where CAST(Created as time) between '23:00:00' and '06:59:59' 

But no results are returned.

Do I need to convert my times to datetimes?

like image 470
TrueEddie Avatar asked Jul 01 '13 14:07

TrueEddie


People also ask

How can I get data between two timestamps in SQL?

As stated above, the format of date and time in our table shall be yyyy:mm: dd hh:mm: ss which is implied by DATETIME2. The time is in a 24-hour format. Syntax: SELECT * FROM TABLE_NAME WHERE DATE_TIME_COLUMN BETWEEN 'STARTING_DATE_TIME' AND 'ENDING_DATE_TIME';

How do I use between time in SQL?

For example, if I require data from 01/01/2008 to 31/03/2008, using "between" only gives the data from 02/01/2008 to 30/03/2008. Is there any way we can get the data including the dates 01/01/2008 and also 31/03/2008? You may not have given enough information for me to diagnose your problem correctly.

Can we use WHERE two times in SQL?

But yes, you can use two WHERE.


1 Answers

I suspect you want to check that it's after 11pm or before 7am:

select * from MyTable where CAST(Created as time) >= '23:00:00'     or CAST(Created as time) < '07:00:00' 
like image 87
Jon Skeet Avatar answered Oct 15 '22 05:10

Jon Skeet