COUNT function and NULL values in T-SQL

Simple and basic rule: Except for COUNT, aggregate functions ignore null values (Source: https://msdn.microsoft.com/en-us/library/ms173454.aspx). Just remember this rule! But there is a catch to this simple rule. Especially with the COUNT function.

Let us first provide a simple table and values for running a test:


CREATE TABLE t1 (c INT);
GO


INSERT INTO t1
SELECT 2 UNION ALL
SELECT NULL UNION ALL
SELECT 4 UNION ALL
SELECT 5 UNION ALL

SELECT 5 UNION ALL
SELECT NULL UNION ALL
SELECT 1;
GO

After this we will run a simple query with count function exposing the catch.

SELECT
COUNT(c) AS count_num_on_column
,COUNT(*) AS count_num_on_table
,COUNT(1) AS count_num_1
FROM t1;
GO

Result of the query is:

count3

Making it that  COUNT is ignoring NULL values in case when we count on particular column and NOT ignoring NULL values when we count with star COUNT(*) or with a fictional column/value COUNT(1).

COUNT(1) and COUNT(*) are completely interchangeable and both yield same results – both do NOT ignore NULL  values and both return the number of rows of a particular table. It counts all the duplicate values (number 5 repeats two times) and based on results, SQL server counts both observations.  But because of performance issues and wider tables COUNT(*) is to be used with caution.

So next time, when you are counting your table or rows or is simply thinking of NULL values with any of aggregate function (AVG, SUM, MIN, MAX, STDEV, VAR,..), remember the rule that except for COUNT (COUNT_BIG as well), aggregate functions ignore null values.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s