Home > Enterprise >  Multiple between condition SQL
Multiple between condition SQL

Time:12-22

I'm doing an SQL query where I want to get certain data between multiple date range and multiple time range.

My table looks like this :

ID date time
1 2021-01-01 10:00

This is the request i've made :

SELECT * FROM myTable
WHERE (date BETWEEN "2021-01-01" AND "2021-01-05")
OR (date BETWEEN "2021-05-01" AND "2021-05-05")
AND (time date BETWEEN "10:00" AND "11:00")
OR (time date BETWEEN "14:00" AND "15:00")

First I was only using AND operator but it wasn't working as well, I saw some people saying that we can use OR operator for that kind of stuff. But the thing is that my condition here is still wrong because it's not working like I want it to. It returns a date out of the range with time in the range and a date in the range with time out of the range. I want to find only dates that are between every date range AND every time. I can have an infinite number of date range and time range.

CodePudding user response:

and has higher precedence than or. You can use parentheses to force the order of evaluation to the order you want:

SELECT * 
FROM myTable
WHERE ((date BETWEEN "2021-01-01" AND "2021-01-05") OR 
       (date BETWEEN "2021-05-01" AND "2021-05-05"))
      AND
      ((time date BETWEEN "10:00" AND "11:00") OR 
       (time date BETWEEN "14:00" AND "15:00"))
  • Related