SQL Clone
SQLServerCentral is supported by Redgate
 
Log in  ::  Register  ::  Not logged in
 
 
 

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.

SQLStudies

My name is Kenneth Fisher and I am Senior DBA for a large (multi-national) insurance company. I have been working with databases for over 20 years starting with Clarion and Foxpro. I’ve been working with SQL Server for 12 years but have only really started “studying” the subject for the last 3. I don’t have any real "specialities" but I enjoy trouble shooting and teaching. Thus far I’ve earned by MCITP Database Administrator 2008, MCTS Database Administrator 2005, and MCTS Database Developer 2008. I’m currently studying for my MCITP Database Developer 2008 and should start in on the 2012 exams next year. My blog is at www.sqlstudies.com.

Comments

Leave a comment on the original post [sqlstudies.com, opens in a new window]

Loading comments...