MySQL count (*) query Problems

Source: Internet
Author: User

Select count (*) from tablename. The query speed has a great relationship with the table type (4 million pieces of data, InnoDB Table 2 minutes 19 seconds, MyISAM type table less than one second ). This is mainly because the MyISAM Table saves the number of rows in the table and can be directly returned, while the InnoDB table does not save the number of rows, which requires full table scanning.

So how can I speed up this query for an indodb table?

The test is as follows: ID is the primary key, PID is the foreign key, both of which have unique indexes, and name column has no index.

Add the WHERE clause:

Where ID> 0, which is equivalent to 2 minutes and 19 seconds without the WHERE clause.

Where pid> 0, very fast, 3.32 seconds.

Select count (ID) is basically the same as Count.

Select count (name) from tablename it takes more than two minutes to add a where clause to the query.

Summary: For an InnoDB table, use count (*) or count (Primary Key), and add the where Col condition. The Col column is a column other than the auto-increment primary key in the table that has unique constraints on the index. In this way, the query speed will be fast. To avoid full table scanning.

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.