SQL Server: SET ANSI_NULLS Behavior with NULL Comparisons
Understand how SET ANSI_NULLS affects SQL Server's handling of NULL in comparisons, leading to TRUE, FALSE, or UNKNOWN results.
On this page
The short answer
The SET ANSI_NULLS setting in SQL Server dictates how comparison operators like '=' and '<>' behave when one or both operands are NULL. By default, SET ANSI_NULLS is ON. In this mode, any comparison involving NULL using '=' or '<>' results in UNKNOWN. This is because NULL represents an unknown value, and you cannot definitively say if an unknown value is equal to or not equal to another value (or even another unknown value). Consequently, rows where a comparison evaluates to UNKNOWN are excluded from the results of WHERE clauses or IF conditions. When SET ANSI_NULLS is OFF, the behavior changes for '=' and '<>' operators. They treat NULL as a known value that is equivalent to any other NULL. This means comparisons with NULL will return either TRUE or FALSE, never UNKNOWN. However, other comparison operators (like '>', '<', '>=', '<=') continue to return UNKNOWN when NULL is involved, regardless of the ANSI_NULLS setting. The standard and recommended way to check for NULL values is by using the IS NULL or IS NOT NULL operators, which work consistently regardless of the SET ANSI_NULLS setting.
The Meaning and Purpose of NULL
NULL in SQL represents the absence of a value. It is not equivalent to zero for numeric types, nor is it an empty string for character types. Instead, it signifies that a value is unknown or not applicable. Because NULL represents an unknown state, standard SQL dictates that it cannot be directly compared to any value, including another NULL, using equality or inequality operators. Such comparisons do not yield a definitive TRUE or FALSE but rather an UNKNOWN result.
Oracle Database, for instance, notes that while it currently treats a zero-length character string as NULL, this behavior is not guaranteed for future releases, and it's recommended not to equate empty strings with NULLs. Any arithmetic operation involving NULL typically results in NULL, as the outcome remains unknown.
Practical tip
Always use IS NULL and IS NOT NULL for checking NULL values. Keep SET ANSI_NULLS ON to adhere to standard SQL behavior and ensure query predictability across different environments and SQL Server versions. Avoid relying on SET ANSI_NULLS OFF for comparisons, as it deviates from the SQL standard and can lead to unexpected results or portability issues.
Three-Valued Logic: TRUE, FALSE, and UNKNOWN
SQL comparison operators return a Boolean result that can have one of three values: TRUE, FALSE, or UNKNOWN. This three-valued logic is fundamental to how SQL handles comparisons, especially when NULL values are involved.
When a comparison evaluates to UNKNOWN, it behaves similarly to FALSE in the context of a WHERE clause; rows yielding UNKNOWN are filtered out. However, UNKNOWN differs from FALSE in logical operations. For example, NOT FALSE evaluates to TRUE, but NOT UNKNOWN evaluates to UNKNOWN. This distinction is crucial when constructing complex conditional logic.
Default Behavior: SET ANSI_NULLS ON
With SET ANSI_NULLS set to ON, which is the default in SQL Server, comparison operators such as '=' (equals) and '<>' (not equals) will return UNKNOWN if either operand is NULL. This aligns with the SQL standard's principle that an unknown value cannot be definitively compared for equality or inequality.
Consequently, any row where a condition involving NULL evaluates to UNKNOWN will not be included in the query results. This behavior ensures that comparisons are only made against known values, preventing potentially misleading results from comparisons with unknown data.
SELECT 1 = NULL;
-- Result: UNKNOWN
SELECT 1 <> NULL;
-- Result: UNKNOWN
SELECT NULL = NULL;
-- Result: UNKNOWNImpact of SET ANSI_NULLS OFF
When SET ANSI_NULLS is set to OFF, SQL Server alters the behavior of the '=' and '<>' operators. In this mode, these specific operators treat NULL as a known value that is equivalent to any other NULL. This means that a comparison like 'NULL = NULL' or 'NULL <> 10' will return either TRUE or FALSE, rather than UNKNOWN.
It is important to note that this special handling applies only to the '=' and '<>' operators. Other comparison operators (>, <, >=, <=, !=) continue to return UNKNOWN when NULL is involved, irrespective of the SET ANSI_NULLS setting. This deviation from standard SQL behavior can lead to unexpected results and reduced query portability.
SET ANSI_NULLS OFF;
SELECT 1 = NULL;
-- Result: FALSE
SELECT 1 <> NULL;
-- Result: TRUE
SELECT NULL = NULL;
-- Result: TRUEComparison Examples with NULL
Consider a table with a column 'A'. If 'A' contains the value 10 in one row and NULL in another, the behavior of comparisons changes based on SET ANSI_NULLS.
With SET ANSI_NULLS ON: - WHERE A <> 10 will return the row where A = 10, because the row with A = NULL evaluates to UNKNOWN and is excluded. - WHERE A = NULL will return no rows, as any comparison with NULL yields UNKNOWN. With SET ANSI_NULLS OFF: - WHERE A <> 10 will return both the row where A = 10 (evaluates to TRUE) and the row where A = NULL (evaluates to TRUE because '<>' treats NULL as not equal to 10). - WHERE A = NULL will return the row where A = NULL (evaluates to TRUE because '=' treats NULL as equal to NULL). These examples highlight how SET ANSI_NULLS OFF can lead to different outcomes for the same query.
CREATE TABLE TestNull (A INT);
INSERT INTO TestNull (A) VALUES (10), (NULL);
-- SET ANSI_NULLS ON (default)
SELECT * FROM TestNull WHERE A <> 10;
-- Expected Result: Row with A = 10
SELECT * FROM TestNull WHERE A = NULL;
-- Expected Result: No rows
SET ANSI_NULLS OFF;
SELECT * FROM TestNull WHERE A <> 10;
-- Expected Result: Rows with A = 10 and A = NULL
SELECT * FROM TestNull WHERE A = NULL;
-- Expected Result: Row with A = NULL
SET ANSI_NULLS ON; -- Reset to defaultThe Correct Way to Check for NULL: IS NULL and IS NOT NULL
Regardless of the SET ANSI_NULLS setting, the standard and most reliable way to check for the presence or absence of a value is by using the IS NULL and IS NOT NULL operators. These operators are specifically designed to test for NULL values and behave consistently whether SET ANSI_NULLS is ON or OFF.
Using IS NULL and IS NOT NULL ensures that your queries correctly identify rows with missing data and are portable across different SQL environments and configurations. Relying on '=' or '<>' with NULL, especially when SET ANSI_NULLS is OFF, can lead to subtle bugs and make your code harder to maintain.
SELECT * FROM TestNull WHERE A IS NULL;
-- Returns the row with A = NULL
SELECT * FROM TestNull WHERE A IS NOT NULL;
-- Returns the row with A = 10UNKNOWN in WHERE, IF, and Logical Expressions
The UNKNOWN result from comparisons involving NULLs has significant implications within SQL Server's control flow and query processing. In a WHERE clause, any condition that evaluates to UNKNOWN causes the corresponding row to be excluded from the result set, just as if the condition evaluated to FALSE.
This behavior is demonstrated in the following logic: If a condition evaluates to UNKNOWN, it is not considered TRUE for the purpose of filtering rows. Furthermore, when UNKNOWN is negated (e.g., NOT UNKNOWN), the result remains UNKNOWN. This differs from negating FALSE, which results in TRUE. This property is important when using Boolean expressions within IF statements or WHILE loops, where a condition evaluating to UNKNOWN might not trigger the expected code block.
DECLARE @Value INT = NULL;
IF (@Value = 10) -- Evaluates to UNKNOWN
BEGIN
PRINT 'Value is 10';
END
ELSE IF (@Value <> 10) -- Evaluates to UNKNOWN
BEGIN
PRINT 'Value is not 10';
END
ELSE -- This ELSE block is never reached because UNKNOWN is not TRUE or FALSE
BEGIN
PRINT 'Value is UNKNOWN';
END
-- Correct approach:
IF @Value IS NULL
BEGIN
PRINT 'Value is NULL';
END
ELSE IF @Value = 10
BEGIN
PRINT 'Value is 10';
END
ELSE
BEGIN
PRINT 'Value is not 10 and not NULL';
END;Practical Takeaways and Portability
To ensure predictable and standard-compliant behavior, it is strongly recommended to keep SET ANSI_NULLS ON. This setting aligns SQL Server's comparison logic with the SQL standard, making your queries more robust and easier to understand.
Avoid relying on the behavior of SET ANSI_NULLS OFF, as it is a non-standard extension that can lead to issues when migrating code to other database systems or even between different versions of SQL Server. Always use IS NULL and IS NOT NULL for checking for the absence of a value. This practice guarantees that your NULL checks are correct and consistent, regardless of the ANSI_NULLS setting.
When migrating SQL code from other database systems, be aware that NULL handling can vary significantly. Oracle, for example, does not have a SET ANSI_NULLS setting and consistently treats comparisons with NULL as UNKNOWN, except for IS NULL and IS NOT NULL. Understanding these differences is crucial for successful database application development and maintenance.
Things to check
- Verify that SET ANSI_NULLS is ON by default in SQL Server.
- Confirm that comparisons with NULL using '=' or '<>' result in UNKNOWN when SET ANSI_NULLS is ON.
- Confirm that comparisons with NULL using '=' or '<>' result in TRUE or FALSE when SET ANSI_NULLS is OFF.
- Ensure that other comparison operators (>, <, >=, <=) still return UNKNOWN when NULL is involved, regardless of SET ANSI_NULLS.
- Validate that IS NULL and IS NOT NULL work correctly for checking NULLs irrespective of the SET ANSI_NULLS setting.
- Check that UNKNOWN results in WHERE clauses filter out rows.
- Verify that NOT UNKNOWN evaluates to UNKNOWN.
Where this applies
This article focuses on the behavior of SET ANSI_NULLS in SQL Server. Other database systems, such as Oracle, do not have an equivalent setting, and their NULL comparison behavior may differ. Oracle, for instance, consistently returns UNKNOWN for comparisons involving NULL, except for IS NULL and IS NOT NULL. The article does not cover the impact of SET ANSI_NULLS on stored procedures, computed columns, indexes, or the handling of NULLs within aggregate functions and scalar functions.