Difference between mysql and select count

Source: Internet
Author: User

1. Test Environment

OS: Linux
DB: mysql-5.5.18
Table: innodb Storage Engine

The table is defined as follows:

2. test scenario and analysis [number of group_message records in the statistical table]

(1) select count (*) Method

(2) select count (1) Method

(3) select count (col_name) Method

Use

Select count (group_id)

Select count (user_id)

Select count (col_null)

The test results show that both select count (*) and select count (1) use the minimum secondary index group_id. Some may ask why we don't need a shorter primary key index [int type]. This is mainly because, in the innodb Storage engine, the primary key index actually contains indexes and data, scanning primary key indexes is actually scanning physical records at the largest cost. Let's take a look at several select count (col_name), count (group_id) uses the shortest secondary index, because this column is the index column, and count (user_id) uses the composite index, because user_id cannot actually use this index, but the number of records can also be obtained by scanning the index, which is less costly than scanning physical records, this should be an optimization of mysql; count (col_null) you cannot use indexes because the column contains null values, which is the lowest efficiency. In addition, for rows with null values, count (col_null) does not actually count, which is inconsistent with the original intention of counting the number of records in the table. For example, the test table has 852226 records, however, if the col_null column has only one non-empty row, the statistical result is as follows:

3. test conclusion

In mysql, when you need to count the number of records in the selct count table, use count (*) or count (1.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.