Logical Functions

Logical Operators

SQL uses a three-valued logic system with TRUE, FALSE, and NULL representing an “unknown” value.

The basic logical operators AND, OR, and NOT are available. The AND and OR operators are both commutative, meaning that the left and right operands are interchangeable without affecting the output of an operation.

The outcome of every possible logical operation is evident in the following truth tables:

aba AND ba OR b
TRUETRUETRUETRUE
TRUEFALSEFALSETRUE
FALSETRUEFALSETRUE
FALSEFALSEFALSEFALSE
TRUENULLNULLTRUE
NULLTRUENULLTRUE
FALSENULLFALSENULL
NULLFALSEFALSENULL
NULLNULLNULLNULL

aNOT aa IS NULLa IS NOT NULLa = NULL
TRUEFALSEFALSETRUENULL
FALSETRUEFALSETRUENULL
NULLNULLTRUEFALSENULL

Testing if a column value is NULL should be done with a IS NULL and not with a = NULL as the latter will change value a to NULL!

Logical Functions

Beware, the logical operators are turned into proper identifiers by double quoting to avoid clashing with the corresponding operator.

FunctionReturn typeDescriptionExample queryResult
"and"(a, b)booleana AND bSELECT "and"(TRUE, FALSE);false
"not"(a)booleanNOT aSELECT "not"(TRUE);false
"or"(a, b)booleana OR bSELECT "or"(TRUE, FALSE);true
"xor"(a, b)booleana OR b, but NOT a AND bSELECT "xor"(TRUE, TRUE);false