8 solutions to optimize MySQL database performance

Source: Internet
Author: User

This article mainly discusses how to correctly improve the performance of MySQL databases. We mainly provide specific solutions from eight aspects. The following is a detailed description of the solution to improve the performance of the MySQL database.

1. select the most suitable field attribute

MySQL supports access to large data volumes. However, the smaller the table in the MySQL database, the faster the query will be executed on it. Therefore, when creating a table, we can set the field width in the table as small as possible to achieve better performance. For example, when defining the zip code field, if you set it to CHAR (255), it is clear that unnecessary null spaces are added to the database, and even VARCHAR is redundant, because CHAR (6) can well complete the task. Similarly, if possible, we should use MEDIUMINT instead of BIGIN to define integer fields.

Another way to improve efficiency is to set the field to not null whenever possible, so that the database does NOT need to compare NULL values during future queries.

Some text fields, such as "Province" or "gender", can be defined as ENUM. In MySQL, The ENUM type is processed as the numeric data, and the numeric data is processed much faster than the text type. In this way, we can improve the performance of the MySQL database.

2. Use JOIN to replace subqueries (Sub-Queries)

MySQL supports SQL subqueries from 4.1. This technique can use the SELECT statement to create a single column query result and use this result as a filter condition in another query. For example, if you want to delete a customer who has no orders in the basic customer information table, you can use the subquery to retrieve the customer IDs of all orders from the sales information table, then pass the result to the primary query, as shown below:

 
 
  1. DELETE FROM customerinfo  
  2. WHERE CustomerID NOT in (SELECT CustomerID FROM salesinfo ) 

Subqueries can be used to complete SQL operations that require multiple logical steps at a time. At the same time, transactions or tables can be prevented from being locked and can be easily written. However, in some cases, subqueries can be joined more efficiently. For example, if we want to retrieve all users without order records, we can use the following query:

 
 
  1. SELECT * FROM customerinfo  
  2. WHERE CustomerID NOT in (SELECT CustomerID FROM salesinfo ) 

If you use JOIN)... to complete this query, the speed will be much faster. Especially when the salesinfo table has an index on CustomerID, the performance will be better. The query is as follows:

 
 
  1. SELECT * FROM customerinfo  
  2. LEFT JOIN salesinfoON customerinfo.CustomerID=salesinfo.  
  3. CustomerID  
  4. WHERE salesinfo.CustomerID IS NULL 

JOIN)... it is more efficient because MySQL does not need to create a temporary table in the memory to perform the query in two logical steps.

3. Use UNION instead of creating a temporary table manually

MySQL 4.0 and later versions support UNION queries. It can merge two or more SELECT queries in a temporary table. When the query Session on the client ends, the temporary table is automatically deleted to ensure that the MySQL database is neat and efficient. When using UNION to create a query, we only need to use UNION as the keyword to connect multiple SELECT statements. Note that the number of fields in all SELECT statements must be the same. The following example demonstrates a query using UNION.

 
 
  1. SELECT Name, Phone FROM client  
  2. UNION  
  3. SELECT Name, BirthDate FROM author  
  4. UNION  
  5. SELECT Name, Supplier FROM product 

4. Transactions

Although we can use subqueries Sub-Queries), JOIN joins, and UNION) to create various Queries, however, not all database operations can be completed with only one or a few SQL statements. In more cases, a series of statements are needed to complete some work. However, in this case, when a statement in the statement block fails to run, the operation of the entire statement block becomes uncertain.

Imagine that you want to insert data into two associated tables at the same time. This may happen: after the first table is successfully updated, the database suddenly experienced an unexpected situation, as a result, the operations in the second table are incomplete, which may damage the data in the database. To avoid this situation, you should use a transaction. Its function is to either operate successfully or fail each statement in the statement block.

In other words, data consistency and integrity can be maintained in the database. The transaction starts with the BEGIN keyword and ends with the COMMIT keyword. If an SQL operation fails, the ROLLBACK command can restore the MySQL database to the State before the start of in.

 
 
  1. BEGIN;  
  2. INSERT INTO salesinfo SET CustomerID=14;  
  3. UPDATE inventory SET Quantity=11 
  4. WHERE item=’book’;  
  5. COMMIT; 

Another important role of transactions is that when multiple users use the same data source at the same time, they can use the database locking method to provide users with a safe access method, this ensures that user operations are not affected by other users.

5. Lock the table

Although transactions are a very good way to maintain database integrity, they sometimes affect database performance, especially in large application systems. Because the database will be locked during transaction execution, other user requests can only wait until the transaction ends. If a database system has only a few users

The impact of transactions will not be a big problem. But suppose there are thousands of users accessing a MySQL database system at the same time, for example, accessing an e-commerce website, A serious response latency occurs.

In fact, in some cases, we can lock the table to achieve better performance. The following example uses the table locking method to complete the transaction function in the previous example.

 
 
  1. LOCK TABLE inventory WRITE  
  2. SELECT Quantity FROM inventory  
  3. WHEREItem=’book’;  
  4. …  
  5. UPDATE inventory SET Quantity=11 
  6. WHEREItem=’book’;  
  7. UNLOCK TABLES 

Here, we use a SELECT statement to retrieve the initial data. Through some calculations, we use the UPDATE statement to UPDATE the new value to the table. The lock table statement containing the WRITE keyword ensures that no other access is allowed to insert, update, or delete the inventory before the unlock tables command is executed.

6. Use foreign keys

Locking a table can maintain data integrity, but it cannot guarantee data relevance. In this case, we can use the foreign key. For example, a foreign key can ensure that each sales record points to an existing customer. Here, the foreign key can map the CustomerID in the customerinfo table to the CustomerID in the salesinfo table. No record without a valid CustomerID will be updated or inserted into the salesinfo table.

 
 
  1. CREATE TABLE customerinfo  
  2. (  
  3. CustomerID INT NOT NULL ,  
  4. PRIMARY KEY ( CustomerID )  
  5. ) TYPE = INNODB;  
  6.  
  7. CREATE TABLE salesinfo  
  8. (  
  9. SalesID INT NOT NULL,  
  10. CustomerID INT NOT NULL,  
  11. PRIMARY KEY(CustomerID, SalesID),  
  12. FOREIGN KEY (CustomerID) REFERENCES customerinfo  
  13. (CustomerID) ON DELETECASCADE  
  14. ) TYPE = INNODB;  

Note the parameter "on delete cascade" in the example ". This parameter ensures that when a customer record in the customerinfo table is deleted, all records related to this customer in the salesinfo table will also be deleted automatically. If you want to use foreign keys in MySQL, remember to define the table type as the InnoDB type of the Transaction Security table when creating the table. This type is not the default MySQL table type. The defined method is to add TYPE = INNODB In the create table statement. As shown in the example.

7. Use Indexes

Index is a common method to improve database performance. It allows the MySQL database server to retrieve specific rows at a much faster speed than no index, especially when the query statement contains the MAX (), MIN (), and ORDERBY commands, the performance improvement is more obvious. Which fields should be indexed? In general, the index should be built on the fields that will be used for JOIN, WHERE judgment and order by sorting.

Try not to index a field in the database that contains a large number of repeated values. For an ENUM type field, it is very likely that a large number of repeated values appear, such as "province" in customerinfo ".. it is not helpful to create an index on such a field. On the contrary, it may also reduce the performance of the database. When creating a TABLE, we can CREATE an appropriate INDEX at the same time, or use alter table or create index to CREATE an INDEX later.

In addition, MySQL

Full-text indexing and search are supported from version 3.23.23. Full-text index is a FULLTEXT index in MySQL, but it can only be used for tables of the MyISAM type. For a large MySQL database, it is very fast to load data to a TABLE without FULLTEXT indexes and then CREATE an INDEX using alter table or create index. However, if you load data to a table with a FULLTEXT index, the execution will be very slow.

8. Optimized query statements

In most cases, using indexes can increase the query speed. However, if an SQL statement is improperly used, indexes cannot play its due role. The following are some notes. First, it is best to compare fields of the same type. Before MySQL 3.23, this is even a required condition.

For example, you cannot compare an indexed INT field with a BIGINT field. However, in special cases, when a CHAR field is of the same size as a VARCHAR field, you can compare them. Second, do not use functions to operate indexed fields.

For example, when the YEAE () function is used on a DATE field, the index cannot play its due role. Therefore, although the two queries below return the same results, the latter is much faster than the former.

 
 
  1. SELECT * FROM order WHERE YEAR(OrderDate)<2001;  
  2. SELECT * FROM order WHERE OrderDate<”2001-01-01″;  

In the same case, when the numeric field is calculated:

 
 
  1. SELECT * FROM inventory WHERE Amount/7<24;  
  2. SELECT * FROM inventory WHERE Amount<24*7  

The above two queries also return the same results, but the subsequent query will be much faster than the previous one. Third, when searching for a struct field, we sometimes use the LIKE keyword and wildcard. Although this method is simple, it is at the cost of system performance. For example, the following query will compare each record in the table.

 
 
  1. SELECT * FROM books  
  2. WHERE name like “MySQL%” 

However, if the following query is used, the returned results are the same, but the speed is much faster:

 
 
  1. SELECT * FROM books  
  2. WHERE name>=”MySQL”and name<”MySQM” 

Finally, you should note that you should avoid making MySQL automatically convert the data type during the query, because the conversion process also makes the index ineffective. The above content is an introduction to the eight rules for MySQL database performance optimization. I hope you will have some gains.

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.