I’m trying to use Between and OR clause in same SQL statement in SQL Server and every time I’m getting empty result, anyone have an idea about this ? My original SQL is formed like this:
SELECT *
FROM opportunity AS oppt
WHERE oppt.Location='O/S'
OR oppt.Location='Overseas'
AND oppt.OPEN_DATE BETWEEN '2014-01-01 00:00:00.000'
AND '2010-01-01 00:00:00.000'
To add to @RBarryYoung’s answer, I’d also recommend putting brackets around your conditions. This makes it explicit, what you intend to be the outcome/how the conditions should be applied.
i.e.
is different to:
It’s the 2nd of the above that is what you currently have, whereas you probably mean the first.
Read up on Operator Precedence – this tells you in which order, various operators are executed in. In this case
ANDis applied beforeOR. But using brackets appropriately to group your conditions helps remove the risk operator precedence having unintended consequences.I suspect in your case, you are wanting the first of my above examples, which actually you can rationalise down to: