Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

COUNT(*) Includes Null Values?

Tags:

MSDN documentation states:

COUNT(*) returns the number of items in a group. This includes NULL values and duplicates.

How can you have a null value in a group? Can anyone explain the point they're trying to make?

like image 443
Derrick Moeller Avatar asked Nov 18 '16 14:11

Derrick Moeller


People also ask

Does count (*) include NULL?

The notation COUNT(*) includes NULL values in the total. The notation COUNT( column_name ) only considers rows where the column contains a non- NULL value.

Can you count NULL values in SQL?

How to Count SQL NULL values in a column? The COUNT() function is used to obtain the total number of the rows in the result set. When we use this function with the star sign it count all rows from the table regardless of NULL values.

Which of the following would include NULL values while counting?

1)Count doesnot take NULL values, but Count(*) returns NULL values.


1 Answers

If you have this table

Table1:

 Field1    Field2    Field3  ---------------------------    1         1         1   NULL      NULL      NULL    2         2        NULL    1         3         1 

Then

 SELECT COUNT(*), COUNT(Field1), COUNT(Field2), COUNT(DISTINCT Field3)  FROM Table1 

Output Is:

 COUNT(*) = 4; -- count all rows, even null/duplicates   -- count only rows without null values on that field  COUNT(Field1) = COUNT(Field2) = 3   COUNT(Field3) = 2   COUNT(DISTINCT Field3) = 1 -- Ignore duplicates 
like image 79
Juan Carlos Oropeza Avatar answered Oct 08 '22 05:10

Juan Carlos Oropeza