XOR in SQL Server

SELECT name,
   population,
   area
FROM world
WHERE (area > 3000000 XOR population > 250000000) 

The question wants you to answer like this. This is the correct and short way of using 'XOR' for this question.


You can implement a XOR like this - don't forget that the question will require you to use <= to correctly use the XOR operator:

SELECT name
    , population
    , area
FROM world
WHERE (area > 3000000 AND population <= 250000000)
OR (area <= 3000000 AND population > 250000000)

SELECT name,
       population,
       area
  FROM world
 WHERE (area > 3000000) <> /* XOR */ (population > 25000000)

Is briefer albeit less readable. As a general rule, <> or != is a good replacement for logicial XOR.


SELECT name,
       population,
       area
FROM world
WHERE (area > 3000000 AND population <= 25000000) OR   -- big area, small population
      (area <= 3000000 AND population > 25000000)      -- small area, big population

Note that I used <= to represent the "smaller then" condition. This is to avoid a situation where an area equals 3 million km^2 or a population exactly equals 2.5 million. Using < would eliminate data in this case.

Tags:

Sql Server