0
0
SQLquery~5 mins

COUNT(*) vs COUNT(column) difference in SQL - Performance Comparison

Choose your learning style9 modes available
Time Complexity: COUNT(*) vs COUNT(column) difference
O(n)
Understanding Time Complexity

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.

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

As the number of rows grows, the work grows linearly.

Input Size (n)Approx. Operations
1010 checks
100100 checks
10001000 checks

Pattern observation: The number of operations grows directly with the number of rows.

Final Time Complexity

Time Complexity: O(n)

This means the counting work grows in direct proportion to the number of rows.

Common Mistake

[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.

Interview Connect

Understanding how simple counting queries scale helps you explain database performance clearly and confidently.

Self-Check

"What if the column used in COUNT(column) has an index? How would that affect the time complexity?"