Three methods to optimize MySQL database query _ MySQL

Source: Internet
Author: User
In the optimization query, database applications (such as MySQL) mean the operation and use of the tool. Using indexes, using EXPLAIN to analyze and query, and adjusting the internal configuration of MySQL can optimize the query. Any database programmer has the following experience: MySQL with high traffic optimizes MySQL queries.

In the optimization query, database applications (suchMySQL) Means the operation and use of the tool. Use Index and usageEXPLAINAnalysis query and adjustmentMySQLTo optimize the query.

Any database programmer has the following experience: a bad SQL query statement in a high-traffic database driver can seriously affect the running of the entire application, it not only consumes more Database time, but also affects other application components.

Like other disciplines, optimizing query performance is largely dependent on developers' intuition. Fortunately, databases like MySQL come with some assistance tools. This article briefly discusses the three tools: using indexes, analyzing queries using EXPLAIN, and adjusting the internal configuration of MySQL.

#1:Use Index

MySQL allows you to index database tables so that you can quickly search for records without scanning the entire table at the beginning, which significantly speeds up query. Each table can have up to 16 indexes. In addition, MySQL also supports multiple column indexes and full-text searches.

It is very easy to add an index to a table. you only need to call oneCREATE INDEXCommand and specify its domain for the index. List A provides an example:

ListA

Mysql> create index idx_username ON users (username );
Query OK, 1 row affected (0.15 sec)
Records: 1 Duplicates: 0 Warnings: 0

HereUsersTableUsernameTo make sure thatWHEREOrHAVINGClause that referencesSELECTQuery statements run faster than when no index is added. PassSHOW INDEXCommand to check that the index has been created (List B ).

ListB

Mysql> show index from users;
-------------- + ------------- + ----------- + ------------- + ---------- + -------- + -------------- + --------- +
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment |
-------------- + ------------- + ----------- + ------------- + ---------- + -------- + -------------- + --------- +
| Users | 1 | idx_username | 1 | username | A | NULL | YES | BTREE |
-------------- + ------------- + ----------- + ------------- + ---------- + -------- + -------------- + --------- +
1 row in set (0.00 sec)

It is worth noting that indexes are like a double-edged sword. Indexing each field of a table is usually unnecessary and may slow down the operation because MySQL has to re-create indexes for these additional tasks every time it inserts or modifies data in the table. On the other hand, it is not a good idea to avoid indexing each field of a table, because the query operation slows down when the record insertion speed is increased. This requires a balance. for example, when designing an index system, it is wise to consider the table's main functions (data repair and editing.

#2:Optimize query performance

When analyzing query performance, considerEXPLAINThe keyword is also very useful.EXPLAINKeyword is generally placed inSELECTBefore the query statement, used to describeMySQLHow to perform query operations andMySQLNumber of rows to be executed in the returned result set. The following simple example illustrates the process (list C:

ListC

Mysql> explain select city. name, city. district FROM city, country WHERE city. countrycode = country. code AND country. code = 'IND ';
+ ---- + ------------- + --------- + ------- + --------------- + --------- + ------- + ------ + ------------- +
| Id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+ ---- + ------------- + --------- + ------- + --------------- + --------- + ------- + ------ + ------------- +
| 1 | SIMPLE | country | const | PRIMARY | 3 | const | 1 | Using index |
| 1 | SIMPLE | city | ALL | NULL | 4079 | Using where |
+ ---- + ------------- + --------- + ------- + --------------- + --------- + ------- + ------ + ------------- +
2 rows in set (0.00 sec) the query here is based on two table connections.EXPLAINThe keyword describes how MySQL processes the connection between the two tables. It must be clear that the current design requires MySQL to processCountryOne record in the table andCityThe entire 4019 records in the table. This means that other optimization techniques can be used to improve the query method. For example, add the following index (List D) to the city table ):

ListD

Mysql>Create index idx_ccode ON city (countrycode );
Query OK, 4079 rows affected (0.15 sec)
Records: 4079 Duplicates: 0 Warnings: 0

Now, when we re-useEXPLAINWhen querying the keyword, we can see a significant improvement (list E ):

ListE

Mysql> explain select city. name, city. district FROM city, country WHERE city. countrycode = country. code AND country. code = 'IND ';
+ ---- + ------------- + --------- + ------- + --------------- + ----------- + --------- + ------- + ------ + ------------- +
| Id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+ ---- + ------------- + --------- + ------- + --------------- + ----------- + --------- + ------- + ------ + ------------- +
| 1 | SIMPLE | country | const | PRIMARY | 3 | const | 1 | Using index |
| 1 | SIMPLE | city | ref | idx_ccode | 3 | const | 333 | Using where |
+ ---- + ------------- + --------- + ------- + --------------- + ----------- + --------- + ------- + ------ + ------------- +
2 rows in set (0.01 sec)

In this example, MySQL only needs to scan 333 records in the city table to generate a result set, and the number of scan records is almost reduced by 90%! Naturally, database resources are faster to query and more efficient.

#3:Adjust internal variables

MySQL is so open that you can easily adjust its default settings to achieve better performance and stability. Key variables to be optimized are as follows:

  • Change the index buffer length(Key_buffer)

Generally, this variable controls the buffer length to be used when processing index tables (read/write operations. MySQL User Manual points out that this variable can be continuously increased to ensure the optimal performance of the index table, and it is recommended to use 25% of the size of the system memory as the value of this variable. This is one of the most important configuration variables of MySQL. if you are interested in optimizing and improving the system, you can changeKey_buffer_sizeVariable value.

  • Change Table length(Read_buffer_size)

When a query continuously scans a table, MySQL allocates a memory buffer for it.Read_buffer_sizeThe variable controls the size of the buffer. If you think continuous scanning is too slow, you can increase the performance by increasing the variable value and memory buffer size.

  • Sets the maximum number of opened tables.(Table_cache)

This variable controls the maximum number of tables opened by MySQL at any time, thereby controlling the server's ability to respond to input requests. It followsMax_connectionsVariables are closely related and increaseTable_cacheValue can beMySQLOpen more tables, just like addingMax_connectionsThe value can increase the number of connections. When receiving a large number of requests from different databases and tables, consider changing the size of this value.

  • Set a time limit for slow query(Long_query_time)

MySQL has a "slow query log", which automatically records all queries that have not been completed within a specific time range. This log is useful for tracking inefficient or misperforming queries and searching for optimization objects.Long_query_timeThe maximum time limit for variable control, in seconds.

The above discussion provides the usage methods of the three tools used to analyze and optimize SQL queries to improve the performance of your applications. Use them to optimize them happily!

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.