Skip to content
Advertisement

Using multiple nested OR statements in WHERE clause makes query return incorrect results

I have a WHERE clause that has a nested OR statement, as seen here:

The @NeedsFollowUp, @NeedsInitialVacc, and @NeedsTraining variables are all set by the variables above. When one or more of these are set to “1”, the query should return employee entries that match the criteria inside their related statements. For example, if the “NeedsFollowUp” and “NeedsTraining” values are set to “1” then the query should return employees that need a follow-up or employees that need training.

Right now, when I set all three to “1” I receive the combined results I’m looking for, but if any of them are set to null, then the query doesn’t return the correct results.

EDIT: Here’s a reproducible example of what I’m seeing.

I think the way the clauses are set up is causing an issue, but I’m not really sure how to fix this. How can I get the OR statements to work in the way I described above?

Advertisement

Answer

I was able to make the OR clauses work correcting by switching from is null to is not null in my where clauses. Using the minimal example, it would look like this:

Be sure to include an additional clause for when all options are NULL, so that you can return the appropriate number of rows.

Here’s a working version.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement