Overview
Thenull-comparison rule flags comparisons using = NULL or <> NULL. These comparisons always evaluate to NULL (not TRUE or FALSE), which is almost never the intended behavior.
Rule name: null-comparison
Default severity: Error
When This Rule Triggers
This rule triggers when:= NULLappears in a comparison<> NULLappears in a comparisonNULL = <expression>appears in a comparisonNULL <> <expression>appears in a comparison
IS NULLis usedIS NOT NULLis used- Normal equality comparisons (not involving
NULL) are used
Why It Matters
SQL’s Three-Valued Logic
In SQL,NULL represents an unknown value. Comparing anything to an unknown value produces an unknown result:
NULL = NULL→NULL(notTRUE!)NULL <> NULL→NULL(notFALSE!)5 = NULL→NULL5 <> NULL→NULL
WHERE clauses, only rows where the condition is TRUE are returned. Conditions that evaluate to NULL or FALSE filter out the row.
The Bug
NULL.
Examples
Problematic: = NULL
Problematic: = NULL
NULL, never returns any rows. Won’t find rows where id is NULL.Problematic: <> NULL
Problematic: <> NULL
NULL, never returns any rows. Won’t find rows where id is not NULL.Problematic: NULL on left side
Problematic: NULL on left side
NULL.Good: IS NULL
Good: IS NULL
id is NULL. Returns rows where id is NULL.Good: IS NOT NULL
Good: IS NOT NULL
id is not NULL. Returns rows where id has a value.Good: Normal equality comparison
Good: Normal equality comparison
NULL) works as expected.Understanding NULL Semantics
Why NULL = NULL is NULL
NULL represents “unknown.” If you have two unknown values, you can’t determine if they’re equal:
Correct NULL Handling
| What you want | Wrong | Correct |
|---|---|---|
| Is it NULL? | col = NULL | col IS NULL |
| Is it not NULL? | col <> NULL | col IS NOT NULL |
| Is it NULL or 5? | col = NULL OR col = 5 | col IS NULL OR col = 5 |
| Is it distinct from NULL? | N/A | col IS DISTINCT FROM NULL |
COALESCE and NULLIF
For more complex NULL handling:Implementation Details
The rule works by:- Walking the SQL AST to find
A_Exprnodes with kindAEXPR_OP - Checking if the operator is
=or<> - Using the
isNullConsthelper to check if either operand is a NULL constant - Reporting an error at the location of the comparison operator
null_comparison.go