Wednesday, December 29, 2010

SUM with NULL Values in SQL Server

Follow on the SUM with NULL Values in Teradata post, I wanted to check the same thing in SQL Server.

When you SUM a value that is nullable, does it work correctly if there are null values? Here's the test and the result. The answer is yes, it works fine here too; it just requires some change in syntax.

Note that if you set up your flag column as a bit column, you have to add a CONVERT in the SUM since you can't add bit columns.

It is also interesting to note that SQL Server throws the following warning after the results of the first query: "Warning: Null value is eliminated by an aggregate or other SET operation."

DECLARE @rgWork1 TABLE (
    
client      INT         NOT NULL,
    
flag        bit 

);

INSERT INTO @rgWork1 (client, flag) VALUES (1, 1); 

INSERT INTO @rgWork1 (client, flag) VALUES (2, 0);
INSERT INTO @rgWork1 (client, flag) VALUES (3, NULL);

SELECT SUM(CONVERT(INT, flag)) AS FlagSum 

FROM @rgWork1;

SELECT SUM(CONVERT(INT, flag)) AS FlagSum 

FROM @rgWork1
WHERE flag = 1;

SELECT SUM(CONVERT(INT, flag)) AS FlagSum

FROM @rgWork1 
WHERE flag IS NOT NULL;

SELECT SUM(CONVERT(INT, flag)) AS FlagSum 

FROM @rgWork1
WHERE (flag = 1 OR flag IS NOT NULL);

All of these queries return the correct answer of 1.

3 comments:

  1. Of course, you can add SET ANSI_WARNINGS OFF before running a query that you know may contain NULL values if you don't want to see the warning (as in query 1).

    ReplyDelete
  2. Good point Jonathan. A simple fix that cuts down the noise.

    ReplyDelete
  3. I was asked the same question.

    There is table with column named salary which allows null also so can we add 20 to that column even if it contains null. I said no it will give a warning.

    ReplyDelete