I’m trying to build a query that will pull events from a DB based on a series of filters: baseId, title, age, and days it will occur.
Here’s what I’ve got so far:
SELECT * FROM [Events]
WHERE BaseId = 574 AND Title LIKE '%occurs%' AND MinAge <= 5 AND MaxAge >= 5
AND (FreqType = 8 AND (FreqInterval & 2) = 2)
OR (FreqType = 8 AND (FreqInterval & 4) = 4)
Without the OR line, it pulls just fine. With the OR line, it no longer cares about the BaseId, Title, MinAge, and MaxAge columns. Well, it does, but only up to the point where the OR is… and then it pulls all that match after the OR (regardless of the previous AND statements).
How can I get the query to filter by each column, and then also by each FreqInterval I want? I may have more than just 2, 4… could have any combination of 1,2,4,8,16,32, or 64.
Or, is there a way to do a AND (FreqType = 8 AND (FreqInterval & 6) = 6) using a SUM of the FreqInterval? I don’t fully understand bitwise querying.
Add parenthesis:
OR has lower operator precedence than AND, you should put parenthesis around them. You can simplify it further:
And as your suggestion, it’s almost correct, here’s the right one though:
By the way, another term for operator precedence is operator stickiness, if your original query is to be written explicitly, it is this:
That’s akin to
4 * 3 + 5, multiplication has higher precedence than addition, so 3 sticks to 4 instead of 5, so the output is17. If your objective is to output32, you should explicitly stick 3 to 5, put a parenthesis around 3 and 5, i.e.4 * (3 + 5)So on your query that uses OR, to make them stick together, put parenthesis around them.
Nonetheless, just like what you hinted, I like this better ツ