COUNT(*) vs COUNT(column) difference in SQL - Performance Comparison
We want to understand how counting rows in a table changes as the table grows.
Specifically, we compare counting all rows versus counting only rows with a value in a column.
Analyze the time complexity of these two queries.
SELECT COUNT(*) FROM employees;
SELECT COUNT(salary) FROM employees;
The first counts all rows, the second counts only rows where salary is not NULL.
Both queries scan the table rows once.
- Primary operation: Checking each row in the employees table.
- How many times: Once per row, for all rows in the table.
As the number of rows grows, the work grows linearly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The number of operations grows directly with the number of rows.
Time Complexity: O(n)
This means the counting work grows in direct proportion to the number of rows.
[X] Wrong: "COUNT(*) is slower than COUNT(column) because it counts everything."
[OK] Correct: Both scan all rows; COUNT(column) just skips NULLs but still checks each row, so their time grows the same way.
Understanding how simple counting queries scale helps you explain database performance clearly and confidently.
"What if the column used in COUNT(column) has an index? How would that affect the time complexity?"