Search code examples
mysqldatabasexor

Mysql xor operator does not properly work, when one of condition is null


I need to add a clause for select where either a record equals the value or equals null.

select * 
from table 
where column = 123 or column is null;

As a result I get

|column|
  123
  123
  null
  null

When I try to use xor

select * 
from table 
where column = 123 xor column is null;

I get either only 123 records

|column|
  123
  123

or, if there is no 123, I got nothing

|column|

But I need, when there is no 123 records to get only null ones. So basically my desired result will be:

|db column|      |column with 123 clause|    |column with 125 clause|
  123                     123                        null
  123                     123                        null
  null
  null
  124

Could you please help me with this issue?


Solution

  • You want the third and fourth row returned if the first and second are not returned, right? This cannot be expressed with a simple where clause. Try

    select * from table where column=123
      or column is null and not exists
         (select * from table where column=123)
    

    Regarding your xor observation: I assume that

    column=123 xor column is null
    

    is equivalent to

    column=123 and column is not null or
    column<>123 and column is null
    

    But when column = null, the expression column<>123 is false, therefore the overall condition is also false.