Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Multiple between condition SQL

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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"))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading