r/SQL • • Jul 30 '26

Discussion Differences between counts

What is the difference between

COUNT(*)

COUNT(1)

COUNT(column_name)

8 Upvotes

23 comments sorted by

View all comments

Show parent comment

2

u/markwdb3 When in doubt, test it out. Jul 30 '26 edited Jul 30 '26

Below is a brief demo showing that COUNT(NOT_NULL_COLUMN) performs worse than COUNT(*) on MySQL. YMMV on other SQL Engines.

mysql> EXPLAIN ANALYZE
    -> SELECT THING_ID, COUNT(*)
    -> FROM THING_ITEM
    -> GROUP BY THING_ID;

<snip>

1 row in set (6.95 sec)

mysql> EXPLAIN ANALYZE
    -> SELECT THING_ID, COUNT(ITEM)
    -> FROM THING_ITEM
    -> GROUP BY THING_ID;

<snip>

1 row in set (7.51 sec)

Results were similar with repeated trials.

mysql> desc THING_ITEM; -- notice ITEM can never be NULL
 +----------------+--------------+------+-----+---------+----------------+
| Field          | Type         | Null | Key | Default | Extra          |
+----------------+--------------+------+-----+---------+----------------+
| THING_ID       | bigint       | NO   | MUL | NULL    |                |
| ITEM           | varchar(255) | NO   |     | NULL    |                |
+----------------+--------------+------+-----+---------+----------------+
2 rows in set (0.02 sec)

So while for this particular query it was only maybe a 7% difference in performance, it's definitely not NOTHING. And given the NOT NULL constraint on ITEM, we can see that COUNT(ITEM) is doing additional work for nothing.

Demonstration that the two queries gave identical results. (This gives us the diffs, so no output means no discrepancies.)

mysql> SELECT THING_ID, COUNT(*) -- qry1
    -> FROM THING_ITEM
    -> GROUP BY THING_ID
    ->
    -> EXCEPT
    ->
    -> SELECT THING_ID, COUNT(ITEM) -- qry2
    -> FROM THING_ITEM
    -> GROUP BY THING_ID;
Empty set (10.34 sec)

mysql> -- now the other way around , for good measure
    -> SELECT THING_ID, COUNT(ITEM) -- qry2
    -> FROM THING_ITEM
    -> GROUP BY THING_ID
    ->
    -> EXCEPT
    ->
    -> SELECT THING_ID, COUNT(*) -- qry1
    -> FROM THING_ITEM
    -> GROUP BY THING_ID;
Empty set (10.32 sec)

So again, YMMV per SQL engine, but COUNT(*) and COUNT(NOT_NULL_COLUMN) are logically the same, with the latter potentially performing worse. (And as I said in parent comment, if NOT_NULL_COLUMN can potentially be transformed to NULL by the query, then sure, they may be logically distinct.)