I have a column in my table called IsDuplicate
, nullable.
If I want to return all results where IsDuplicate
is '0' or is null, I can do
WHERE ISNULL(IsDuplicate, 0) = 0
or I can do
WHERE IsDuplicate = '0' OR IsDuplicate IS NULL
However, this never works:
WHERE NOT(IsDuplicate = '1')
Why does this not work? This should cover both IsDuplicate
equaling both '0' and NULL.
3条答案
按热度按时间i86rm4rw1#
Nulls aren't really a value. They are the absence value. You can see this in where clauses:
instead of
Bar could = 1, or it could be 34, or could have no value at all.
For example, I currently have 2 legs, 2 arms, and null tails. Is my tail a mouse tail? I don't have a tail to check against.
So for SQL, unless you specifically address the null they get ignored.
wgx48brx2#
In SQL Server the treatment of comparisons and boolean operators involving
NULL
values are influenced by the setting ofANSI_NULLS
option. When this option isON
, and theIsDuplicate
isNULL
the result of bothIsDuplicate = '1'
andNOT(IsDuplicate = '1')
isUNKNOWN
(notFALSE
).For a row to be returned the
WHERE
condition should evaluate toTRUE
(notNULL
orUNKNOWN
).Check these:
Results of boolean operators involving
NULL
s andUNKNOWN
s https://learn.microsoft.com/en-us/sql/t-sql/language-elements/null-and-unknown-transact-sql?view=sql-server-ver16and how
ANSI_NULLS
option workshttps://learn.microsoft.com/en-us/sql/t-sql/statements/set-ansi-nulls-transact-sql?view=sql-server-ver16
And why
NOT
operator returnsUNKNOWN
fromUNKNOWN
:https://learn.microsoft.com/en-us/sql/t-sql/language-elements/not-transact-sql?view=sql-server-ver16
7z5jn7bk3#
In SQL, when comparing values, the result can be true or false or unknown. i.e. a "3 way logic" applies.
So, for
NOT (some_value = 1)
if some_value is NULL, the result of the expression will be unknown instead of true or false, and this means that rows with NULL values will not be returned by this expression.i.e. for "where NOT(unknown)"; the NOT cannot reverse unknown into true or false, so it remains unknown and is therefore excluded from the result.
refer: The Three-Valued Logic of SQL