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

The difference between count(1) and count(*)

function describe
count(*) Count all rows, including null rows (COUNT(*) will not only scan the entire table, but also scan each field of the table. And COUNT('x') or COUNT(COLUMN) or COUNT(0 ), etc., only perform a full table scan of one field)
count(1) Calculate the total number of qualifying rows, and will not ignore null values ​​(in fact, it can be understood that there is such a field in the table, this field is the fixed value 1, count(1), which is to calculate the total number of 1's. In the same way, count (2), it is also possible, the values ​​obtained are exactly the same, count('x'), count('y') are both possible. count(*), when executed, will translate the asterisk into the specific name of the field, the effect It’s the same, but there is one more translation action, which is slightly less efficient than the fixed value method.)
count(column name) Query the count of the column name. If the field is null, no statistics will be counted (null here does not refer to the empty string or 0, but to null). That is, if the value of a certain field is NULL, no statistics will be counted.

1.1 Create table sql

CREATE TABLE Person(
	id int,
	name varchar(20)
)engine myisam charset utf8;

insert into Person 
values(1,'lisi');

insert into Person
values(2,null);

insert into Person
values(null,null);
  1. select * from Person;

image.png

  1. select count(*) from Person;

image.png

  1. select count(name) from Person;

image.png

  1. select count(1) from Person;

image.png

1.2 Execution efficiency

There will be slight differences between the three according to different situations, and MySQL will optimize count(*).
(1) count(*) includes all columns, which is equivalent to the number of rows. When calculating the results, NULL column values ​​will not be ignored.
(2) count(1) includes ignoring all columns, using 1 to represent code lines. When counting results, column values ​​​​that are NULL will not be ignored.
(3) count (column name) only includes the column with the column name. When calculating the results, empty column values ​​will be ignored.
(4) If the column is the primary key, count(column name) is more efficient than count(1)
(5) If the column is not the primary key, count(1) is more efficient than count(column name)
(6) If there is a primary key in the table, count (primary key column name) is the most efficient
(7) If there is only one column in the table, count(*) is the most efficient
(8) If the table has multiple columns and there is no primary key, then count(1) is more efficient than count( *)
(9) count(1) is the same as count(primary key), only the primary key is scanned. count(*) is the same as count (non-primary key), scanning the entire table. Obviously the former
is faster.
(10) count(*) ≈ count(1) > count(id) > count(field)

Guess you like

Origin blog.csdn.net/hansome_hong/article/details/127430392