DEV Community

Cover image for Understanding MySQL Query Optimizer: COUNT(id) vs COUNT(*)
Darko Todorić
Darko Todorić

Posted on

Understanding MySQL Query Optimizer: COUNT(id) vs COUNT(*)

In MySQL, we use "COUNT" functions almost every day to help us calculate the number of rows for a given query. The biggest dilemma of every developer regarding performance is whether it is better to use "COUNT(*)" or "COUNT(id)".


MySQL Optimizer

MySQL optimizer is a critical component of MySQL responsible for determining the most efficient way to execute a given SQL query. This part plays a key role in the dilemma of which "COUNT" is the fastest. So let's explain...

We create the "users" table, which will have an index on the "first_name" column:

CREATE table users (
    id int NOT NULL AUTO_INCREMENT,
    first_name varchar(256) NOT NULL,
    PRIMARY KEY (id),
    INDEX idx_first_name (first_name)
);
Enter fullscreen mode Exit fullscreen mode

We add a few rows and run the following 2 queries:

EXPLAIN SELECT COUNT(id) FROM users;
Enter fullscreen mode Exit fullscreen mode
EXPLAIN SELECT COUNT(*) FROM users;
Enter fullscreen mode Exit fullscreen mode

When you run these 2 SQL queries, you will notice that they use the same index, "COUNT(*)" is not slower at all, the MySQL Optimizer is responsible for that, which finds the index in the table that will give the best performance. In this case, both queries will return data at the same speed, because they use the same index and because the MySQL optimizer decided that that index is the most efficient.

MySQL Optimizer considers many parameters that contribute to choosing the best index key so that the given query returns data as quickly as possible.


Conclusion

The use of "COUNT(*)" is generally recommended because it allows the MySQL Optimizer to choose the most efficient approach, while "COUNT(column_name)" can be specifically useful in situations where it is necessary to count only non-NULL values ​​in a particular column. Understanding how the MySQL Optimizer works and how to use indexes is critical to achieving optimal query performance.

Top comments (0)