sqlsql-serverlogic

Simpler way to do IS NOT DISTINCT FROM


Is the following the simplest way to write out the IS NOT DISTINCT FROM without using that clause?

   ColA IS NULL AND ColB IS NOT NULL 
OR ColA IS NOT NULL AND ColB IS NULL
OR ColA != ColB

Or is there a simpler way?


Solution

  • IS [NOT] DISTINCT FROM is the simplest way of doing this.

    On previous versions you can do (Fiddle)

    though the more verbose

    sometimes gives a better execution plan for the IS DISTINCT case (example).

    See Undocumented Query Plans: Equality Comparisons for some discussion on various alternative approaches for this.

    Generally I've found execution plans are fine with the above approaches though occasionally I have found writing out the condition in full as

    does give a better execution plan.

    The INTERSECT/EXCEPT are very convenient when you need to do this type of comparison across multiple columns...

    EXISTS (SELECT t1.colA, t1.colB, t1.colC 
            INTERSECT 
            SELECT t2.colA, t2.colB, t2.colC)
    

    ... but check the plans to see that they are being optimised efficiently in the context you are using them.