I am trying to figure out the simplest generalized SQL expression that can check if two columns a
and b
are the same. In other words, an expression that evaluates to true
when:
a
isNULL
andb
isNULL
; ora
is notNULL
andb
is notNULL
anda = b
Assume columns a
and b
have exactly the same data type.
The most obvious solution, which I'm using in the below example, is horribly convoluted, particularly because I need to repeat this clause 15x in a 15-column table:
SELECT * FROM (
SELECT 'x' a, 'x' b FROM dual
UNION ALL
SELECT 'x' a, NULL b FROM dual
UNION ALL
SELECT NULL a, 'x' b FROM dual
UNION ALL
SELECT NULL a, NULL b FROM dual
UNION ALL
SELECT 'x' a, 'y' b FROM dual
UNION ALL
SELECT 'x' a, NULL b FROM dual
UNION ALL
SELECT NULL a, 'y' b FROM dual
UNION ALL
SELECT NULL a, NULL b FROM dual
)
WHERE (a IS NULL AND b IS NULL) OR
(a IS NOT NULL AND b IS NOT NULL AND a = b)
/
And the expected result is:
+--------+--------+
| a | b |
+--------+--------+
| x | x |
| (null) | (null) |
| (null) | (null) |
+--------+--------+
tl;dr - Can I simplify my WHERE
clause, ie make it more compact, while keeping it logically correct?
P.S.: I couldn't give a damn about any SQL purist insistence that "NULL
is not a value". For my practical purposes, if a
contains NULL
and b
does not, then a
differs from b
. It is not "unknown" whether they differ. So please, in advance, no arguments up that alley!
P.P.S.: My SQL flavour is Oracle 11g.
P.P.P.S.: Someone decided this question is a duplicate of "Is there better Oracle operator to do null-safe equality check?" but a cursory check in that question will show that the answers are less helpful than the ones posted on this thread and do not satisfy my particular, and explicitly-stated criteria. Just because they are similar doesn't make them duplicates. I've never understood why people on SO work so hard to force my problem X to be someone else's problem Y.