MySQL count efficiency

count() is an aggregate function. For the returned result set, judge line by line. If the parameter of the count function is not NULL, the accumulated value will be incremented by 1, otherwise it will not be incremented. Finally, the cumulative value is returned.

  • For count (primary key id), the InnoDB engine traverses the entire table, takes out the id value of each row, and returns it to the server layer. After the server layer gets the id, it is judged that it is impossible to be empty, so it is added up by line.
  • For count(1), the InnoDB engine traverses the entire table, but does not take a value. The server layer puts a number "1" in each row returned, judging that it is impossible to be empty, and accumulating it by row.

Just look at the difference between these two usages, you can compare it, count(1) executes faster than count(primary key id). Because returning the id from the engine will involve the operation of parsing the data row and copying the field value;

  • For count (field):

1. If the "field" is defined as not null, read the field line by line from the record, judge that it cannot be null, and add up by line;
2. If the "field" definition is allowed to be null, then when executing , It is judged that it is possible to be null, and the value is taken out and judged again, and it is accumulated if it is not null.

But count(*) is an exception. It will not take out all the fields, but is specially optimized and does not take values. count(*) is definitely not null, accumulate by line.

Summary: Sort by efficiency (count(*) is recommended)

count(field)<count(primary key id)<count(1)≈count(*)

Guess you like

Origin blog.csdn.net/qq_36807862/article/details/102232301