Counting NULLs

,

Recently I was doing one of Kendra Little’s (b/t) SQL Server quizzes. Specifically the Quiz: COUNT() in SQL Server. As always I enjoy these quizzes and in this particular case it gave me an idea for a post.

How do NULL values affect the COUNT function?

Here are three different ways to COUNT:

Count the number of values
SELECT COUNT(FieldName) FROM TableName;
-- or
SELECT COUNT(ALL FieldName) FROM TableName;

The ALL argument is the default and is unnecessary (I didn’t even know it existed until I started this post). Here you are counting the number of non NULL values in FieldName. So in a column with (1, NULL, 1, 2, 3, NULL, 1) you’ll get a count of 5. You do get a nice warning (depending on your ANSI_WARNINGS setting) if there was a NULL value though.

Warning: NULL value is eliminated by an aggregate or other SET operation.

Count the distinct number of values
SELECT COUNT(DISTINCT FieldName) FROM TableName;

Here we get the number of DISTINCT non NULL values. Using the same list of values, (1, NULL, 1, 2, 3, NULL, 1), this time you’ll get 3. Really this is the same as the regular COUNT (warnings, nulls etc) with the one exception that, currently at least, you can’t use windowing functions with COUNT DISTINCT.

Count the number of rows
SELECT COUNT(*) FROM TableName;
-- or
SELECT COUNT(1) FROM TableName;

Here we are counting the number of rows in the table. NULLs don’t really matter here because we aren’t counting any particular column. You can use a * or any literal. 1, ‘a’, ‘1/1/1900’ it doesn’t matter. In fact, you can even use 1/0 (from what I can tell the value used is not evaluated in a similar way to the field list in an EXISTS.)

ANSI_NULLS

ANSI_NULLS does not appear to have any effect on COUNT.

Rate

Share

Share

Rate