search
HomeDatabaseMysql TutorialMySQL optimization summary-total number of queries

This article mainly introduces the MySQL optimization summary-the total number of queries. The article conducts a simple test and comparison, which has certain reference value. Friends who need it can learn about it. I hope it can help everyone.

1, COUNT(*) and COUNT(COL)

COUNT(*) usually performs an index scan on the primary key, while COUNT(COL) Not necessarily. In addition, the former is the total number of all matching records in the statistical table, while the latter is the number of all matching COL records in the calculation table. There are differences.
Optimization summary, for MyISAM tables:

1. SELECT COUNT(*) FROM tablename is the best choice under any circumstances;

2. Try your best Reduce SELECT COUNT(*) FROM tablename WHERE COL = 'value' queries;

3. Eliminate the occurrence of SELECT COUNT(COL) FROM tablename WHERE COL2 ='value'.

2. COUNT(*) or COUNT(id)

According to my understanding, it should be faster to use COUNT(id). Because if my id is an auto-incrementing primary key, then calculating its number will obviously consume less resources than calculating the number of all fields. However, I have seen in more than one article similar to guiding mysql query acceleration that it is recommended that we use SELECT COUNT(*) instead of direct COUNT primary key. Why is this?

It seems that the table using the MyISAM engine stores the total number of entries. If there is no WHERE or WHERE is always true (such as WHERE 1), then COUNT(*) can directly return the total number of entries.

In addition, it is obvious that COUNT(*) does not "calculate all fields". Obviously MySQL will parse * into "a piece of data".

Test data, simple comparison, no more in-depth testing:


#0.817-一百万条的查询时间
select count(*) from student ;
#0.789-一百万条的查询时间
select count(id) from student;
#1.011-一百万条的查询时间
select count(name) from student;
#1.162-一百万条的查询时间
SELECT COUNT(*) FROM student WHERE namelike '%xiaoli%';#默认用主键索引查询,但是加上like条件后索引失效

Generally speaking, using COUNT(id) is still better It's faster. Here is a simple comparison for your reference.

Related recommendations:

Example sharing of IN to INNER JOIN for mysql optimization

Summary of some commonly used mysql optimization methods

Summary of commonly used mysql optimization sql statement query methods

The above is the detailed content of MySQL optimization summary-total number of queries. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
How to copy table structure and data in MySQLHow to copy table structure and data in MySQLApr 29, 2025 pm 03:18 PM

The methods of copying table structure and data in MySQL include: 1. Use CREATETABLE...LIKE to copy the table structure; 2. Use INSERTINTO...SELECT to copy the data. Through these steps, data backup and migration can be efficiently performed in different scenarios.

How to get data randomly from MySQL tableHow to get data randomly from MySQL tableApr 29, 2025 pm 03:15 PM

Randomly fetching data from MySQL tables can be done using the RAND() function. 1. Basic usage: SELECTFROMusers ORDERBYRAND()LIMIT5; 2. Advanced usage: SELECTFROMusersWHEREid>=(SELECTFLOOR(RAND()*(SELECTMAX(id)FROMusers)))LIMIT5; Optimization strategy includes using index and pagination query.

Index optimization strategies and methods for MySQL tablesIndex optimization strategies and methods for MySQL tablesApr 29, 2025 pm 03:12 PM

The index optimization strategies of MySQL tables include: 1. Create indexes for frequently queried columns; 2. Use joint indexes to improve the efficiency of multi-column query; 3. Check and optimize indexes regularly to avoid abuse and failure; 4. Select appropriate index types and columns, monitor and optimize indexes, and write efficient query statements. Through these methods, MySQL query performance can be significantly improved.

How to optimize data update and delete operations in MySQLHow to optimize data update and delete operations in MySQLApr 29, 2025 pm 03:09 PM

Optimizing data update and deletion operations in MySQL can be achieved through the following steps: 1. Use indexes, such as CREATEINDEXidx_last_order_dateONcustomers(last_order_date); 2. Perform batch operations to reduce locking time; 3. Avoid full table scanning, use appropriate indexes and WHERE clauses; 4. Use transactions to improve performance and atomicity; 5. Monitor and optimize, and use slow query logs to identify performance bottlenecks.

How to modify the default port number of MySQLHow to modify the default port number of MySQLApr 29, 2025 pm 03:06 PM

The method to modify the default MySQL port number is: 1. Open the configuration file sudonano/etc/my.cnf; 2. Add or modify port=3307 in the [mysqld] section; 3. Save and exit the editor; 4. Restart the MySQL service sudosystemctlrestartmysql, which can improve the security of the database and resolve port conflict issues.

How to optimize the initial configuration parameters of MySQLHow to optimize the initial configuration parameters of MySQLApr 29, 2025 pm 03:03 PM

Adjusting MySQL initial configuration parameters can significantly improve database performance. 1. Setting innodb_buffer_pool_size to 4GB can reduce disk I/O of InnoDB tables and improve query performance. 2. In a high concurrency environment, setting innodb_thread_concurrency to 0 can improve performance, but the number of threads needs to be managed with caution.

How does MySQL handle concurrency compared to other RDBMS?How does MySQL handle concurrency compared to other RDBMS?Apr 29, 2025 am 12:44 AM

MySQLhandlesconcurrencyusingamixofrow-levelandtable-levellocking,primarilythroughInnoDB'srow-levellocking.ComparedtootherRDBMS,MySQL'sapproachisefficientformanyusecasesbutmayfacechallengeswithdeadlocksandlacksadvancedfeatureslikePostgreSQL'sSerializa

How does MySQL handle transactions compared to other relational databases?How does MySQL handle transactions compared to other relational databases?Apr 29, 2025 am 12:37 AM

MySQLhandlestransactionseffectivelyusingtheInnoDBengine,supportingACIDpropertiessimilartoPostgreSQLandOracle.1)MySQLusesREPEATABLEREADasthedefaultisolationlevel,whichcanbeadjustedtoREADCOMMITTEDforhigh-trafficscenarios.2)Itoptimizesperformancewithabu

See all articles

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

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment