The difference between count (*), count (1), and count (column name)

count is the simplest aggregation function, let's talk about their differences?

From the execution results:

        There is no difference between count(1) and count(*) because neither count(1) nor count(*) will filter null values,

        But there is a difference in count (column name), because count (column name) will filter null values.

In terms of execution efficiency:

        There are some differences between them according to different situations, and MySQL will optimize count(*).

        (1) If the column is the primary key, count (column name) is more efficient than count (1)

        (2) If the column is not the primary key, count (1) is more efficient than count (column name)

        (3) If there is a primary key in the table, count (primary key column name) has the best efficiency

        (4) If there is only one column in the table, count(*) has the best efficiency

        (5) If there are multiple columns in the table and there is no primary key, then count(1) is more efficient than count(*)

Supplementary note:

        count(1), in fact, is to calculate how many eligible rows there are.

        1 does not mean the first field, but a fixed value.

        In fact, it can be thought of as a field in the table, this field is a fixed value 1, count (1) is to calculate how many 1s there are in total,

        count(*), when executed, * will be translated into the specific name of the field, the effect is the same, but there is one more translation action, which is slightly less efficient than the fixed value method.

Guess you like

Origin blog.csdn.net/m0_60252632/article/details/124107047