1

I have a table

num
----
NULL
NULL
NULL
NULL
55
NULL
NULL
NULL
99

when I wrote

select COUNT(*) 
from tbl
where num is null

the output was 7

but when I wrote

select COUNT(num) 
from tbl
where num is null

the output was 0

what's the difference between these two queries ??

yogi
  • 19,175
  • 13
  • 62
  • 92
  • A possible duplicate of this question http://stackoverflow.com/questions/3003457/count-vs-countcolumn-name-which-is-more-correct – praveen Jun 14 '12 at 06:48
  • possible duplicate of [In SQL, what's the difference between count(column) and count(*)?](http://stackoverflow.com/questions/59294/in-sql-whats-the-difference-between-countcolumn-and-count) – Damien_The_Unbeliever Jun 14 '12 at 06:51

5 Answers5

3

Difference is in the field you select.

When counting COUNT(*) NULL values are taken into account (count all rows returned).

When counting COUNT(num) NULL values are NOT taken into account (count all non-null fields).

That is a standard behavior in SQL, whatever the DBMS used

Source. look at COUNT(DISTINCT expr,[expr...])

Elzo Valugi
  • 27,240
  • 15
  • 95
  • 114
Arnaud F.
  • 8,252
  • 11
  • 53
  • 102
0

count(*) returns number of rows, count(num) returns number of rows where num is not null. Change your last query to select count(*) from test where num is null to get the result you expect.

Krzysztof Kozielczyk
  • 5,887
  • 37
  • 28
0

Count(*) counts the number of rows, COUNT(num) counts the number of not-null values in column num.

shobhit
  • 702
  • 2
  • 9
  • 21
Frank Schmitt
  • 30,195
  • 12
  • 73
  • 107
  • But there are two `NOT-NULL` values there in `num` column so when the output was 0 don't you think that it should be 2 ?? – yogi Jun 14 '12 at 06:51
  • 2
    That would be the case if you hadn't added this where clause: where num is null :-) – Frank Schmitt Jun 14 '12 at 07:02
0

In second case first count values are eliminated and then where clause comes in picture. While in first case when you are using * row with null is not eliminated.

If you are counting on a coll which contains null and you want rows with null to be included in count than use

 Count(ISNULL(col,0))
ejb_guy
  • 1,125
  • 6
  • 6
-1

Considering the output given above, the result of the query count(num) should be 2.

shadab shah
  • 551
  • 1
  • 6
  • 8