SQL - WHERE query with combination of XOR and AND on two variables

I have two column names foo

and bar

from a table. I want to return any string that returns true under conditions imposed on X

and Y

. I want to combine conditions in the table below in a section of where

my query select

.

   X      |    Y     |  conditions
----------+----------+----------------
   null   |   null   | 
 not null |   null   |  foo=X
   null   | not null |  bar=Y
 not null | not null |  foo=X and bar=Y

      

Here X

and Y

are variables that are substituted into the request. They both are never zero, so we don't care about the first condition. But if one value is null, the condition checks the other (XOR). If both values ​​are nonzero, the condition checks both (AND). This is the query I have so far, but is there anything simpler and cleaner for the part where

?

select
      ...
where
     (X is not null and Y is not null and
      foo=X and bar=Y)
  or (X is not null and
      Y is null and foo=X)
  or (X is null and
      Y is not null and bar=Y)

      

EDIT Note: foo

and bar

can be null.

+3


source to share


1 answer


You can simplify the condition by noticing that the pair X, foo

is independent of the pair Y, bar

. Therefore, you can simplify the condition like this:



WHERE (X is NULL OR foo=X) AND (Y is NULL OR bar=Y)

      

+3


source







All Articles