Published on

February 1, 2015

Understanding NULL in SQL Server

Working with NULL values in SQL Server can be challenging for many developers. It is important to understand how NULL works and how it can affect your queries and operations. In this blog post, we will explore the concept of NULL and discuss how to handle it effectively.

In a previous blog post, we discussed two important set options in SQL Server – Quoted Identifier and ANSI NULL. These options can impact how NULL values are handled in your queries. If you haven’t read that blog post, I highly recommend checking it out for a better understanding of these set options.

Today, we will focus on another set option called ANSI_WARNINGS. This option controls the display of warning messages related to NULL values. Let’s take a look at some examples to see how it works.

SET NOCOUNT ON

DECLARE @ItemSale TABLE (
    ID INT,
    Qty INT,
    Price MONEY
)

INSERT INTO @ItemSale (ID, Qty, Price)
SELECT 1, 25, 100

INSERT INTO @ItemSale (ID, Qty, Price)
SELECT 2, NULL, 200

INSERT INTO @ItemSale (ID, Qty, Price)
SELECT 3, 5, NULL

SELECT SUM(Qty) 'Sum - 1' FROM @ItemSale WHERE ID IN (1, 3) -- no warning

SELECT SUM(Price) 'Sum - 2' FROM @ItemSale WHERE ID IN (1, 3) -- Warning: Null value is eliminated by an aggregate or other SET operation.

SELECT AVG(Qty) 'Avg' FROM @ItemSale WHERE ID IN (1, 2) -- Warning: Null value is eliminated by an aggregate or other SET operation.

In the above example, we have a table called @ItemSale with three columns – ID, Qty, and Price. We insert some data into this table, including NULL values. When we perform aggregate functions like SUM and AVG on the columns containing NULL values, SQL Server displays a warning message indicating that the NULL values are being ignored.

To suppress these warning messages, we can use the SET ANSI_WARNINGS OFF option before executing the script. This option tells SQL Server to ignore the warnings related to NULL values.

SET ANSI_WARNINGS OFF

-- Rest of the script goes here

By adding the SET ANSI_WARNINGS OFF option, we can see that the warning messages are no longer displayed in the output.

It is important to note that the default value of the ANSI_WARNINGS setting is OFF, which is generally a good practice. However, it is crucial to understand the implications of turning this setting ON. In some scenarios, it may be necessary to suppress these warning messages, but it should be done with caution.

In future blog posts, we will cover other errors and warnings that can be suppressed using the same set option. Stay tuned for more insights into SQL Server!

Have you ever deliberately turned on the ANSI_WARNINGS setting? If so, we would love to hear about your scenario and how it was useful. Share your experiences in the comments below!

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.