


What is the difference between count(*), count(1), and count(col) in MySQL?
count Function
COUNT(expression): Returns the total number of queried records. The expression parameter is a field or * sign.
Test
MySQL version: 5.7.29
Create a user table and insert one million pieces of data, of which half a million rows in the gender field are null Value of
CREATE TABLE `users` ( `Id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id', `name` varchar(32) DEFAULT NULL COMMENT '名称', `gender` varchar(20) DEFAULT NULL COMMENT '性别', `create_date` datetime DEFAULT NULL COMMENT '创建时间', PRIMARY KEY (`Id`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='用户表';
count(*)
Prior to MySQL 5.7.18, InnoDB processed statements by scanning the clustered index. SELECT COUNT(*) Starting in MySQL 5.7.18, InnoDB handles SELECT COUNT(*) statements by traversing the smallest available secondary index, unless the index or optimizer hint instructs the optimizer to use a different index. If the secondary index does not exist, the clustered index is scanned.
The general meaning is that if there is a secondary index, use the secondary index. If there are multiple secondary indexes, the smallest secondary index will be preferred to reduce costs. If there is no secondary index, use the clustered index.
The following tests are used to verify these views.
First of all, query the execution plan when there is only the primary key index of Id.
You can see that the type is index, which means that the index is used. The key is PRIMARY, which means the primary key index is used, key_len=8.
Next, add an index to the name field, and use the execution plan again to view
You can see that the index is also used, but the index uses name The index of the field, key_len=99.
Then add an index to the create_date field while retaining the name field index, and check the execution plan again
#You can see that this time the The create_date field is indexed, key_len=6.
No matter which index is used above, the total number of rows finally queried is one million, regardless of whether they contain NULL values.
count(1)
count(1) has the same query results as count(*), and ultimately returns one million pieces of data, regardless of whether they contain NULL values.
count(col)
count(col) counts the value of a certain column, which is divided into three situations:
count(id): counts id
The query results are the same as count(*), and ultimately one million pieces of data are returned.
count(index col): Statistics of indexed fields
Use count(name) For query, the execution plan is as follows:
You can see that the index field is used for statistics, and the index is also hit.
Set the name field in a column to NULL, and then perform a count query. The result returns 999999
Then set the NULL value of this column to an empty string, and then Perform a count query, and the result returns 1000000
. Therefore, in summary, simply using the index field to count the number of rows can hit the index, and only count the number of rows that are not NULL values.
count(normal col): Count fields without indexes
If you count fields without indexes, the index will not be used, and only the number of rows that are not NULL values will be counted.
Count(1) and count(*) trade-off
I don’t know where I saw or heard about it before, count(1) is better than count(*) count(*) is highly efficient, which is a wrong perception. There is a saying on the official website, InnoDB handles SELECT COUNT( *) and SELECT COUNT(1) operations in the same way. There is no performance difference.
Translation The bottom line is that InnoDB handles SELECT COUNT(*) and SELECT COUNT(1) operations in the same way, with no performance difference.
For MyISAM tables, COUNT(*) is optimized to return very quickly if retrieving from one table, no other columns are retrieved and there is no clause. This optimization only applies to MyISAM tables because for this The storage engine stores the exact number of rows and can be accessed very quickly. COUNT(1) does the same optimization only if the first column is defined as NOT NULL. ----From MySQL official website
These optimizations are based on the premise that there is no where and group by.
It is also mentioned in the Alibaba development specifications
So if you can use count(*) during development, just use count(*).
The above is the detailed content of What is the difference between count(*), count(1), and count(col) in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

TograntpermissionstonewMySQLusers,followthesesteps:1)AccessMySQLasauserwithsufficientprivileges,2)CreateanewuserwiththeCREATEUSERcommand,3)UsetheGRANTcommandtospecifypermissionslikeSELECT,INSERT,UPDATE,orALLPRIVILEGESonspecificdatabasesortables,and4)

ToaddusersinMySQLeffectivelyandsecurely,followthesesteps:1)UsetheCREATEUSERstatementtoaddanewuser,specifyingthehostandastrongpassword.2)GrantnecessaryprivilegesusingtheGRANTstatement,adheringtotheprincipleofleastprivilege.3)Implementsecuritymeasuresl

ToaddanewuserwithcomplexpermissionsinMySQL,followthesesteps:1)CreatetheuserwithCREATEUSER'newuser'@'localhost'IDENTIFIEDBY'password';.2)Grantreadaccesstoalltablesin'mydatabase'withGRANTSELECTONmydatabase.TO'newuser'@'localhost';.3)Grantwriteaccessto'

The string data types in MySQL include CHAR, VARCHAR, BINARY, VARBINARY, BLOB, and TEXT. The collations determine the comparison and sorting of strings. 1.CHAR is suitable for fixed-length strings, VARCHAR is suitable for variable-length strings. 2.BINARY and VARBINARY are used for binary data, and BLOB and TEXT are used for large object data. 3. Sorting rules such as utf8mb4_unicode_ci ignores upper and lower case and is suitable for user names; utf8mb4_bin is case sensitive and is suitable for fields that require precise comparison.

The best MySQLVARCHAR column length selection should be based on data analysis, consider future growth, evaluate performance impacts, and character set requirements. 1) Analyze the data to determine typical lengths; 2) Reserve future expansion space; 3) Pay attention to the impact of large lengths on performance; 4) Consider the impact of character sets on storage. Through these steps, the efficiency and scalability of the database can be optimized.

MySQLBLOBshavelimits:TINYBLOB(255bytes),BLOB(65,535bytes),MEDIUMBLOB(16,777,215bytes),andLONGBLOB(4,294,967,295bytes).TouseBLOBseffectively:1)ConsiderperformanceimpactsandstorelargeBLOBsexternally;2)Managebackupsandreplicationcarefully;3)Usepathsinst

The best tools and technologies for automating the creation of users in MySQL include: 1. MySQLWorkbench, suitable for small to medium-sized environments, easy to use but high resource consumption; 2. Ansible, suitable for multi-server environments, simple but steep learning curve; 3. Custom Python scripts, flexible but need to ensure script security; 4. Puppet and Chef, suitable for large-scale environments, complex but scalable. Scale, learning curve and integration needs should be considered when choosing.

Yes,youcansearchinsideaBLOBinMySQLusingspecifictechniques.1)ConverttheBLOBtoaUTF-8stringwithCONVERTfunctionandsearchusingLIKE.2)ForcompressedBLOBs,useUNCOMPRESSbeforeconversion.3)Considerperformanceimpactsanddataencoding.4)Forcomplexdata,externalproc


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version
SublimeText3 Linux latest version

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

SublimeText3 English version
Recommended: Win version, supports code prompts!

Dreamweaver Mac version
Visual web development tools
