Table of Contents
1.Which one is faster, COUNT(1), COUNT(*) or COUNT(field)?
4. Summary
Home Database Mysql Tutorial What is the performance principle of MySQL COUNT(*)

What is the performance principle of MySQL COUNT(*)

May 27, 2023 am 10:49 AM
mysql

1.Which one is faster, COUNT(1), COUNT(*) or COUNT(field)?

Execution effect:

  • ##COUNT(*)MySQL performs count(*) In order to optimize, count(*) directly scans the primary key index record, does not take out all fields, and directly accumulates them by row.

  • 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. Accumulate by row.

  • COUNT(field)If this "field" is defined as NOT NULL, then the InnoDB engine will read this field from the record line by line, the server layer The judgment cannot be NULL and is accumulated row by row; if the "field" definition allows NULL, then the InnoDB engine will read this field from the record row by row, and then take out the value and judge it again. If it is not NULL, it will be accumulated.

Experimental Analysis

The environment used for testing in this article:

[root@zhyno1 ~]# cat /etc/system-release
CentOS Linux release 7.9.2009 (Core)

[root@zhyno1 ~]# uname -a
Linux zhyno1 3.10.0-1160.62.1.el7.x86_64 #1 SMP Tue Apr 5 16:57:59 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux
Copy after login

The test database uses (storage engine Using InnoDB, other parameters are default):

(Mon Jul 25 09:41:39 2022)[root@GreatSQL][(none)]>select version();
+-----------+
| version() |
+-----------+
| 8.0.25-16 |
+-----------+
1 row in set (0.00 sec)
Copy after login

Experiment start:

#首先我们创建一个实验表

CREATE TABLE test_count (
  `id` int(10) NOT NULL AUTO_INCREMENT PRIMARY KEY,
  `name` varchar(20) NOT NULL,
  `salary` int(1) NOT NULL,
  KEY `idx_salary` (`salary`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

#插入1000W条数据
DELIMITER //
CREATE PROCEDURE insert_1000w()
BEGIN
    DECLARE i INT;
    SET i=1;
    WHILE i<=10000000 DO
        INSERT INTO test_count(name,salary) VALUES(&#39;KAiTO&#39;,1);
        SET i=i+1;
    END WHILE;
END//
DELIMITER ;
#执行存储过程
call insert_1000w();
Copy after login

Next, let’s experiment separately:

COUNT(1)It took 4.19 seconds

(Sat Jul 23 22:56:04 2022)[root@GreatSQL][test]>select count(1) from test_count;
+----------+
| count(1) |
+----------+
| 10000000 |
+----------+
1 row in set (4.19 sec)
Copy after login

COUNT(*)It took 4.16 seconds

(Sat Jul 23 22:57:41 2022)[root@GreatSQL][test]>select count(*) from test_count;
+----------+
| count(*) |
+----------+
| 10000000 |
+----------+
1 row in set (4.16 sec)
Copy after login

COUNT (Field)It took 4.23 seconds

(Sat Jul 23 22:58:56 2022)[root@GreatSQL][test]>select count(id) from test_count;
+-----------+
| count(id) |
+-----------+
|  10000000 |
+-----------+
1 row in set (4.23 sec)
Copy after login

We can test the execution plan again

COUNT(*)

(Sat Jul 23 22:59:16 2022)[root@GreatSQL][test]>explain select count(*) from test_count;
+----+-------------+------------+------------+-------+---------------+------------+---------+------+---------+----------+-------------+
| id | select_type | table      | partitions | type  | possible_keys | key        | key_len | ref  | rows    | filtered | Extra       |
+----+-------------+------------+------------+-------+---------------+------------+---------+------+---------+----------+-------------+
|  1 | SIMPLE      | test_count | NULL       | index | NULL          | idx_salary | 4       | NULL | 9980612 |   100.00 | Using index |
+----+-------------+------------+------------+-------+---------------+------------+---------+------+---------+----------+-------------+
1 row in set, 1 warning (0.01 sec)

(Sat Jul 23 22:59:48 2022)[root@GreatSQL][test]>show warnings;
+-------+------+-----------------------------------------------------------------------+
| Level | Code | Message                                                               |
+-------+------+-----------------------------------------------------------------------+
| Note  | 1003 | /* select#1 */ select count(0) AS `count(*)` from `test`.`test_count` |
+-------+------+-----------------------------------------------------------------------+
1 row in set (0.00 sec)
Copy after login

COUNT(1)

(Sat Jul 23 23:12:45 2022)[root@GreatSQL][test]>explain select count(1) from test_count;
+----+-------------+------------+------------+-------+---------------+------------+---------+------+---------+----------+-------------+
| id | select_type | table      | partitions | type  | possible_keys | key        | key_len | ref  | rows    | filtered | Extra       |
+----+-------------+------------+------------+-------+---------------+------------+---------+------+---------+----------+-------------+
|  1 | SIMPLE      | test_count | NULL       | index | NULL          | idx_salary | 4       | NULL | 9980612 |   100.00 | Using index |
+----+-------------+------------+------------+-------+---------------+------------+---------+------+---------+----------+-------------+
1 row in set, 1 warning (0.00 sec)

(Sat Jul 23 23:13:02 2022)[root@GreatSQL][test]>show warnings;
+-------+------+-----------------------------------------------------------------------+
| Level | Code | Message                                                               |
+-------+------+-----------------------------------------------------------------------+
| Note  | 1003 | /* select#1 */ select count(1) AS `count(1)` from `test`.`test_count` |
+-------+------+-----------------------------------------------------------------------+
1 row in set (0.00 sec)
Copy after login

COUNT(field)

(Sat Jul 23 23:13:14 2022)[root@GreatSQL][test]>explain select count(id) from test_count;
+----+-------------+------------+------------+-------+---------------+------------+---------+------+---------+----------+-------------+
| id | select_type | table      | partitions | type  | possible_keys | key        | key_len | ref  | rows    | filtered | Extra       |
+----+-------------+------------+------------+-------+---------------+------------+---------+------+---------+----------+-------------+
|  1 | SIMPLE      | test_count | NULL       | index | NULL          | idx_salary | 4       | NULL | 9980612 |   100.00 | Using index |
+----+-------------+------------+------------+-------+---------------+------------+---------+------+---------+----------+-------------+
1 row in set, 1 warning (0.00 sec)

(Sat Jul 23 23:13:29 2022)[root@GreatSQL][test]>show warnings;
+-------+------+-----------------------------------------------------------------------------------------------+
| Level | Code | Message                                                                                       |
+-------+------+-----------------------------------------------------------------------------------------------+
| Note  | 1003 | /* select#1 */ select count(`test`.`test_count`.`id`) AS `count(id)` from `test`.`test_count` |
+-------+------+-----------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
Copy after login

It should be noted that if there is a non-primary key field in COUNT

(Tue Jul 26 14:01:57 2022)[root@GreatSQL][test]>explain select count(name) from test_count where id <100 ;
+----+-------------+------------+------------+-------+---------------+---------+---------+------+------+----------+-------------+
| id | select_type | table      | partitions | type  | possible_keys | key     | key_len | ref  | rows | filtered | Extra       |
+----+-------------+------------+------------+-------+---------------+---------+---------+------+------+----------+-------------+
|  1 | SIMPLE      | test_count | NULL       | range | PRIMARY       | PRIMARY | 4       | NULL |   99 |   100.00 | Using where |
+----+-------------+------------+------------+-------+---------------+---------+---------+------+------+----------+-------------+
1 row in set, 1 warning (0.00 sec)
Copy after login

Experimental results

  • 1. From the above experiment we can conclude that

    COUNT(*) and COUNT(1) is the fastest, followed by COUNT(id).

  • 2.

    count(*) was rewritten by the MySQL query optimizer into count(0), and the idx_salary index was selected.

  • 3.

    count(1) and count(id) both select the idx_salary index.

Experimental conclusion

Summary:

COUNT(*)=COUNT(1)>COUNT(id)

MySQL's official documentation also says:

InnoDB handles SELECT COUNT(*) and SELECT COUNT(1) operations in the same way. There is no performance difference

Translation: InnoDB handles SELECT COUNT(*) and SELECT COUNT(1) operations in the same way. There is no performance difference

So it means that for

COUNT(1) or COUNT(*), the optimization of MySQL is actually exactly the same, there is no There is no performance difference.

But it is recommended to use

COUNT(*), because this is the standard syntax for counting rows defined by MySQL92.

2.COUNT(*) and TABLES_ROWS

In InnoDB, the space occupied by each table of the MySQL database and the number of rows recorded in the table can be opened by opening the MySQL

information_schema database . There is a TABLES table in this library. The main fields of this table are:

  • TABLE_SCHEMA: Database name

  • TABLE_NAME:Table name

  • ENGINE:Storage engine used

  • TABLES_ROWS: Number of records

  • DATA_LENGTH: Data size

  • INDEX_LENGTH: Index Size

TABLE_ROWS is used to display how many rows the table currently has. This command is executed very quickly. Can this TABLE_ROWS replace

count(*)?

We use TABLES_ROWS to query the number of table records:

(Sat Jul 23 23:15:14 2022)[root@GreatSQL][test]>SELECT TABLE_ROWS
    -> FROM INFORMATION_SCHEMA.TABLES
    -> WHERE TABLE_NAME = &#39;test_count&#39;;
+------------+
| TABLE_ROWS |
+------------+
|    9980612 |
+------------+
1 row in set (0.03 sec)
Copy after login

You can see that the number of records is not accurate because the TABLES_ROWS row count under the InnoDB engine is only Approximate estimate.

3. How is COUNT(*) executed?

The first thing to make clear is that MySQL has many different engines. In different engines,

count(*) There are different implementation methods. This article mainly introduces the execution process on the InnoDB engine.

In the InnoDB storage engine, the

count(*) function first reads from the memory. Get the data in the table into the memory buffer, and then scan the entire table to get the number of row records. To put it simply, it is a full table scan. A loop solves the problem. Within the loop: First read a row, and then decide whether the row is included in count. The loop counts row by row.

In the MyISAM engine, the total number of rows of a table is stored on the disk, so when executing

count(*), this number will be returned directly, which is very efficient.

The reason why InnoDB does not store numbers like MyISAM is because even if there are multiple queries at the same time, due to multi-version concurrency control (MVCC), the number of rows that the InnoDB table should return does not matter. definite. InnoDB performs better than MyISAM in terms of transaction support, concurrency or data security.

Despite this, InnoDB has optimized the count(*) operation. InnoDB is an index-organized table. The leaf nodes of the primary key index tree are data, while the leaf nodes of the ordinary index tree are primary key values. Therefore, the ordinary index tree is much smaller than the primary key index tree. For operations like count(*), the results obtained by traversing any index tree are logically the same. Therefore, the MySQL optimizer will find the smallest tree to traverse.

It should be noted that What we discuss in this article is count(*) without filter conditions. If the WHERE condition is added, the MyISAM engine The table cannot return so quickly.

4. Summary

  • ##1.

    COUNT(*)=COUNT(1)>COUNT(id)

  • 2. The usage of COUNT function is mainly used to count the number of table rows. The main usages are

    COUNT(*), COUNT(field) and COUNT(1)

  • ##3. Because
  • COUNT(*)

    is SQL92 The defined standard syntax for counting the number of rows, so MySQL has made a lot of optimizations for it. MyISAM will directly record the total number of rows in the table for COUNT(*) query, while InnoDB will scan the table When choosing the smallest index to reduce costs. The premise of these optimizations is that there are no WHERE and GROUP conditional queries.

  • 4. In InnoDB, there is no difference in implementation between
  • COUNT(*)

    and COUNT(1), and the efficiency is the same, but COUNT(field)Needs to judge whether the field is NULL, so the efficiency will be lower.

  • 5. Because
  • COUNT(*)

    is the standard syntax for counting rows defined by SQL92 and is highly efficient, it is recommended to use COUNT(* )The number of rows in the query table.

  • 6. Just like the previous use case of
  • COUNT(name)

    , during the table creation process, it is necessary to establish a high-performance index according to business needs, and also pay attention to Avoid unnecessary indexing.

The above is the detailed content of What is the performance principle of MySQL COUNT(*). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1243
24
MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

MySQL and phpMyAdmin: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

MySQL vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Solve database connection problem: a practical case of using minii/db library Solve database connection problem: a practical case of using minii/db library Apr 18, 2025 am 07:09 AM

I encountered a tricky problem when developing a small application: the need to quickly integrate a lightweight database operation library. After trying multiple libraries, I found that they either have too much functionality or are not very compatible. Eventually, I found minii/db, a simplified version based on Yii2 that solved my problem perfectly.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

MySQL for Beginners: Getting Started with Database Management MySQL for Beginners: Getting Started with Database Management Apr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

Solve MySQL mode problem: The experience of using the TheliaMySQLModesChecker module Solve MySQL mode problem: The experience of using the TheliaMySQLModesChecker module Apr 18, 2025 am 08:42 AM

When developing an e-commerce website using Thelia, I encountered a tricky problem: MySQL mode is not set properly, causing some features to not function properly. After some exploration, I found a module called TheliaMySQLModesChecker, which is able to automatically fix the MySQL pattern required by Thelia, completely solving my troubles.

See all articles