Wednesday, March 20, 2013

On COUNT(*)

"The discovery of truth is prevented more effectively, not by the false appearance things present and which mislead into error, not directly by weakness of the reasoning powers, but by preconceived opinion, by prejudice."
-- Arthur Schopenhauer

I made a discovery today, much to my chagrin it seems that COUNT returns 0 only when it is presented an empty table, not when it is presented an empty group.  It seems that I am not the first to make this discovery and I do not think I will be the last.

Here are some examples to illustrate what I am talking about:

SELECT *
  FROM dbo.tbl
;

(empty)

SELECT COUNT(*)
  FROM dbo.tbl
;

COLUMN_0
0


SELECT COUNT(*)
  FROM dbo.tbl
  GROUP BY value
;

(empty)

SELECT COUNT(*) OVER (PARTITION BY value)
  FROM dbo.tbl
;

(empty)

SELECT COUNT(value)
  FROM dbo.tbl
;

COLUMN_0
0


SELECT COUNT(value)
  FROM dbo.tbl
  GROUP BY value
;


(empty)

The above can be found on SQL Fiddle.