ByteBoard Notes Notes

Compare COUNT(*) and COUNT(column) on a column with NULL values

Informatics Practices XII · Experiment 35 of 38 · SQL

12-IPSQL queries
Expt. No.35
Page No.70

COUNT(*) vs COUNT(column)

Aim

To show the difference between COUNT(*) and COUNT(marks) when some marks are NULL.

Concepts used

Queries

USE school;SELECT COUNT(*), COUNT(marks), COUNT(name) FROM student;SELECT AVG(marks), SUM(marks) / COUNT(*) FROM student;

A marked line continues the line above it. In your file, write it on the same line.

Table used

Table: student
+-----+-------+-------+
| sid | name  | marks |
+-----+-------+-------+
|   1 | Asha  |    82 |
|   2 | Rohan |  NULL |
|   3 | Ira   |    88 |
|   4 | Kabir |  NULL |
|   5 | Diya  |    74 |
+-----+-------+-------+

Output

mysql> USE school; Database changed
mysql> SELECT COUNT(*), COUNT(marks), COUNT(name) FROM student; +----------+--------------+-------------+ | COUNT(*) | COUNT(marks) | COUNT(name) | +----------+--------------+-------------+ | 5 | 3 | 5 | +----------+--------------+-------------+ 1 row in set
mysql> SELECT AVG(marks), SUM(marks) / COUNT(*) FROM student; +------------+-----------------------+ | AVG(marks) | SUM(marks) / COUNT(*) | +------------+-----------------------+ | 81.3333 | 48.8000 | +------------+-----------------------+ 1 row in set

✓ Printed by running this query set, not typed by hand.

Result

COUNT(*) counted all 5 rows but COUNT(marks) only 3, because two marks are NULL. AVG(marks) divided by 3 (81.3333), while SUM(marks) / COUNT(*) divided by 5 (48.8000).

Viva voce: what the examiner may ask

01What does COUNT(*) count?

Every row, whatever its values.

02What does COUNT(marks) count?

Only the rows where marks is not NULL.

03Why are the two averages different?

AVG ignores NULL rows; dividing by COUNT(*) treats them as if they were 0.

Variations for the lab test

  1. Count the students whose marks are NULL using WHERE marks IS NULL.
  2. Count students scoring above 80.
  3. Count the distinct marks (not in the syllabus for IP; skip DISTINCT).
! Common mistake Using COUNT(marks) to find the number of students undercounts when marks are missing; use COUNT(*).
Back to the 12-IP index