Published on

May 13, 2013

Understanding SQL Server’s ANSI_NULLS Setting

Have you ever encountered a situation where executing two different queries in SQL Server produced almost identical results? If so, the key reason behind this behavior might be the ANSI_NULLS setting. In this blog post, we will explore the concept of ANSI_NULLS and its impact on query results.

Before we dive into the details, let’s quickly recap what ANSI_NULLS is. ANSI_NULLS is a setting in SQL Server that determines how NULL values are treated in comparisons. When ANSI_NULLS is set to ON, any comparison involving a NULL value will result in UNKNOWN, which is treated as false. On the other hand, when ANSI_NULLS is set to OFF, comparisons involving NULL values will return true or false based on the comparison operator used.

To illustrate the impact of ANSI_NULLS, let’s consider a puzzle. In the puzzle, we have two queries that produce different results when ANSI_NULLS is set to ON. However, when we change the ANSI_NULLS setting to OFF, the results of the two queries become almost identical. The question is, why?

The answer lies in how the IN and NOT IN operators handle NULL values. When ANSI_NULLS is ON, the IN operator treats NULL as a separate value and includes it in the result set if it matches any of the values in the list. Conversely, the NOT IN operator excludes NULL from the result set. However, when ANSI_NULLS is OFF, both the IN and NOT IN operators treat NULL as a regular value and include it in the result set if it matches any of the values in the list.

Let’s take a look at the following example:

-- Original Puzzle
SET ANSI_NULLS ON;

-- Query 1
SELECT 'SQLAuthority' AS Statement11
WHERE 'Authority' IN ('S','Q', 'L', 'Authority', NULL);

-- Query 2
SELECT 'SQLAuthority' AS Statement12
WHERE 'Authority' NOT IN ('S','Q', 'L', NULL);

-- Puzzle Solution
SET ANSI_NULLS OFF;

-- Query 3
SELECT 'SQLAuthority' AS Statement11
WHERE 'Authority' IN ('S','Q', 'L', 'Authority', NULL);

-- Query 4
SELECT 'SQLAuthority' AS Statement12
WHERE 'Authority' NOT IN ('S','Q', 'L', NULL);

In the above example, when ANSI_NULLS is ON, Query 1 includes the NULL value in the result set because it matches one of the values in the list. However, Query 2 excludes the NULL value from the result set. When ANSI_NULLS is OFF, both Query 3 and Query 4 include the NULL value in the result set.

Understanding the behavior of ANSI_NULLS is crucial when writing queries that involve NULL values. By being aware of how the setting affects comparisons, you can ensure accurate and consistent results.

That’s all for this blog post. We hope you found it informative and helpful in understanding SQL Server’s ANSI_NULLS setting. Stay tuned for more SQL Server tips and tricks!

Click to rate this post!
[Total: 0 Average: 0]

Let's work together

Send us a message or book free introductory meeting with us using button below.