user1399007
user1399007

Reputation: 43

SQL select records between two hours

I have a table with two fields that describe opening hours of each store - "from" and "to" in 24h format integers. I created a search page that allows user to find stores that are open at given hour.

I don't really know how to create the SQL query, the main problem is that there are two cases.

One case is that from value is bigger than to value, for example from 23 to 5 and it gives two intervals 23 to 24 and 1 to 5.

Second case is when to value is bigger than from value (say from 8 to 22), where I get one interval.

Any idea how to create the query, that would work in those two cases?

Upvotes: 1

Views: 564

Answers (1)

dani herrera
dani herrera

Reputation: 51715

Let's supose this table schema:

store
id  fromH  toH
 1     23   5
 2      8  22

and a parameter @T (the hour you are looking for)

Then select is:

select *
from store
where 
  ( fromH < toH and @t between fromH and toH ) or
  ( fromH > toH and 
         (@t between fromH and 24 OR
         (@t between 1 and toH )
  )

Explaining

Select all fields from stores that:

  • start open hour > close open hour and your hour is between both.
  • or
  • start open hour < close open hour and your hour is between open hour and 24h OR 1h and close hour.

Upvotes: 1

Related Questions