Table of Contents
2. Use Union to optimize the Like statement
3. Avoid using expressions with leading wildcard characters
4. Make full use of MySQL’s full-text search
5. Optimize the database schema
Normalization
Use the best data type
Avoid NULL
Home Database Mysql Tutorial How to optimize MYSQL query? Introduction to mysql query optimization methods

How to optimize MYSQL query? Introduction to mysql query optimization methods

Oct 08, 2018 pm 05:03 PM
mysql optimization

The content of this article is about the simple implementation code of process pool in python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Add indexes on all columns used for where, order by and group by

except index It can ensure that a record is uniquely marked, and it can also enable the MySQL server to obtain results from the database faster. Indexes also play a very important role in sorting.

Mysql's index may occupy additional space and reduce the performance of insertion, deletion and update to a certain extent. However, if your table has more than 10 rows of data, indexing can greatly reduce the search execution time.

It is highly recommended to use "worst case data samples" to test MySql queries to get a clearer understanding of how the query will behave in production.

Suppose you are executing the following query statement in a database table with more than 500 rows:

mysql>select customer_id, customer_name from customers where customer_id='345546'
Copy after login

The above query will force the Mysql server to perform a full table scan to obtain the data being sought.

model, Mysql provides a special Explain statement to analyze the performance of your query statement. When you add a query statement after the keyword, MySql will display all the information the optimizer has about the statement.

If we use the explain statement to analyze the above query, we will get the following analysis results:

mysql> explain select customer_id, customer_name from customers where customer_id='140385';
+----+-------------+-----------+------------+------+---------------+------+---------+------+------+----------+-------------+
| id | select_type | table     | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra       |
+----+-------------+-----------+------------+------+---------------+------+---------+------+------+----------+-------------+
|  1 | SIMPLE      | customers | NULL       | ALL  | NULL          | NULL | NULL    | NULL |  500 |    10.00 | Using where |
+----+-------------+-----------+------------+------+---------------+------+---------+------+------+----------+-------------+
Copy after login

As you can see, the optimizer displays very important information, which can help us Fine-tune database tables. First, MySql will perform a full table scan because the key column is Null. Secondly, the MySql server has made it clear that it will scan 500 rows of data to complete this query.

In order to optimize the above query, we only need to add an index m on the customer_id column:

mysql> Create index customer_id ON customers (customer_Id);
Query OK, 0 rows affected (0.02 sec)
Records: 0  Duplicates: 0  Warnings: 0
Copy after login

If we execute the explain statement again, we will get the following results :

mysql> Explain select customer_id, customer_name from customers where customer_id='140385';
+----+-------------+-----------+------------+------+---------------+-------------+---------+-------+------+----------+-------+
| id | select_type | table     | partitions | type | possible_keys | key         | key_len | ref   | rows | filtered | Extra |
+----+-------------+-----------+------------+------+---------------+-------------+---------+-------+------+----------+-------+
|  1 | SIMPLE      | customers | NULL       | ref  | customer_id   | customer_id | 13      | const |    1 |   100.00 | NULL  |
+----+-------------+-----------+------------+------+---------------+-------------+---------+-------+------+----------+-------+
Copy after login

From the above output results, it is obvious that the MySQL server will use the index customer_id to query the table. You can see that the number of rows to be scanned is 1. Although I am only executing this query on a table with 500 rows, the index is even more optimized when retrieving a larger data set.

2. Use Union to optimize the Like statement

Sometimes, you may need to use the or operator in the query for comparison. When the or keyword is used too frequently in the where clause, it may cause the MySQL optimizer to mistakenly choose a full table scan to retrieve records. The union clause can make queries execute faster, especially when one of the queries has an optimized index and the other query also has an optimized index.

For example, when there are indexes on first_name and last_name, execute the following query statement:

mysql> select * from students where first_name like 'Ade%' or last_name like 'Ade%'
Copy after login

The above query and the following use union Compared with merging two queries that fully utilize the query statement, the speed is much slower.

mysql> select * from students where first_name like 'Ade%' union all select * from students where last_name like 'Ade%'
Copy after login

3. Avoid using expressions with leading wildcard characters

Mysql cannot use the index when there is a leading wildcard character in the query. Taking the student table above as an example, the following query will cause MySQL to perform a full table scan and add an index to the first_name field in time.

mysql> select * from students where first_name like '%Ade'
Copy after login

Use explain analysis to get the following results:

mysql> explain select * from students where first_name like  '%Ade'  ;
+----+-------------+----------+------------+------+---------------+------+---------+------+------+----------+-------------+
| id | select_type | table    | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra       |
+----+-------------+----------+------------+------+---------------+------+---------+------+------+----------+-------------+
|  1 | SIMPLE      | students | NULL       | ALL  | NULL          | NULL | NULL    | NULL |  500 |    11.11 | Using where |
+----+-------------+----------+------------+------+---------------+------+---------+------+------+----------+-------------+
Copy after login

As shown above, Mysql will scan all 500 rows of data, which will make the query extremely slow.

If you are faced with using wildcard characters to query data, but do not want to reduce the performance of the database, you should consider using MySQL’s full-text search (FTS). Because it is much faster than wildcard query. In addition to this, FTS is able to return better quality relevant results.

The statement to add a full-text search index to the student sample table is as follows:

mysql> alter table students add fulltext(first_name, last_name)';
mysql> select * from students where match(first_name, last_name) against ('Ade');
Copy after login

In the above example, we specified the search keyword Ade that we want to match Columns (first_name, last_name). If the query optimizer executes the above statement, you will get the following results:

mysql> explain Select * from students where match(first_name, last_name) AGAINST ('Ade');
+----+-------------+----------+------------+----------+---------------+------------+---------+-------+------+----------+-------------------------------+
| id | select_type | table    | partitions | type     | possible_keys | key        | key_len | ref   | rows | filtered | Extra                         |
+----+-------------+----------+------------+----------+---------------+------------+---------+-------+------+----------+-------------------------------+
|  1 | SIMPLE      | students | NULL       | fulltext | first_name    | first_name | 0       | const |    1 |   100.00 | Using where; Ft_hints: sorted |
+----+-------------+----------+------------+----------+---------------+------------+---------+-------+------+----------+-------------------------------+
Copy after login

5. Optimize the database schema

Normalization

First, normalize all database tables, even if possible There will be some losses. For example, if you need to create two tables to record customers and orders data, you should reference the customer by customer ID in the orders table, not the other way around. The diagram below shows the database architecture designed without any data redundancy.

How to optimize MYSQL query? Introduction to mysql query optimization methods

In addition, use the same data type class to store similar values.

Use the best data type

MySQL supports various data types, including integer, float, double, date, datetime, varchar, text, etc. When designing database tables, you should try to use the shortest data type that can satisfy the characteristics.

For example, if you are designing a system user table and the number of users will not exceed 100, you should use the 'TINYINT' type for user_ud. The value range of this type is -128 to 128. If a field needs to store date type values, it is better to use datetime type, because there is no need to perform complex type conversion when querying.

When the values ​​are all numeric types, use Integer. Values ​​of type Integer are faster than values ​​of type Text when performing calculations.

Avoid NULL

NULL means that the column has no value. You should avoid these types of values ​​if possible because they can harm database results. For example, you need to get the sum of the amounts of all orders in the database, but the amount in an order record is null. If you don't pay attention to the null pointer, it is likely to cause exceptions in the calculation results. In some cases, you may need to define a default value for a column.


The above is the detailed content of How to optimize MYSQL query? Introduction to mysql query optimization methods. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
Laravel Introduction Example Laravel Introduction Example Apr 18, 2025 pm 12:45 PM

Laravel is a PHP framework for easy building of web applications. It provides a range of powerful features including: Installation: Install the Laravel CLI globally with Composer and create applications in the project directory. Routing: Define the relationship between the URL and the handler in routes/web.php. View: Create a view in resources/views to render the application's interface. Database Integration: Provides out-of-the-box integration with databases such as MySQL and uses migration to create and modify tables. Model and Controller: The model represents the database entity and the controller processes HTTP requests.

MySQL and phpMyAdmin: Core Features and Functions MySQL and phpMyAdmin: Core Features and Functions Apr 22, 2025 am 12:12 AM

MySQL and phpMyAdmin are powerful database management tools. 1) MySQL is used to create databases and tables, and to execute DML and SQL queries. 2) phpMyAdmin provides an intuitive interface for database management, table structure management, data operations and user permission management.

MySQL vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Solve database connection problem: a practical case of using minii/db library Solve database connection problem: a practical case of using minii/db library Apr 18, 2025 am 07:09 AM

I encountered a tricky problem when developing a small application: the need to quickly integrate a lightweight database operation library. After trying multiple libraries, I found that they either have too much functionality or are not very compatible. Eventually, I found minii/db, a simplified version based on Yii2 that solved my problem perfectly.

Laravel framework installation method Laravel framework installation method Apr 18, 2025 pm 12:54 PM

Article summary: This article provides detailed step-by-step instructions to guide readers on how to easily install the Laravel framework. Laravel is a powerful PHP framework that speeds up the development process of web applications. This tutorial covers the installation process from system requirements to configuring databases and setting up routing. By following these steps, readers can quickly and efficiently lay a solid foundation for their Laravel project.

Solve MySQL mode problem: The experience of using the TheliaMySQLModesChecker module Solve MySQL mode problem: The experience of using the TheliaMySQLModesChecker module Apr 18, 2025 am 08:42 AM

When developing an e-commerce website using Thelia, I encountered a tricky problem: MySQL mode is not set properly, causing some features to not function properly. After some exploration, I found a module called TheliaMySQLModesChecker, which is able to automatically fix the MySQL pattern required by Thelia, completely solving my troubles.

Explain the purpose of foreign keys in MySQL. Explain the purpose of foreign keys in MySQL. Apr 25, 2025 am 12:17 AM

In MySQL, the function of foreign keys is to establish the relationship between tables and ensure the consistency and integrity of the data. Foreign keys maintain the effectiveness of data through reference integrity checks and cascading operations. Pay attention to performance optimization and avoid common errors when using them.

Compare and contrast MySQL and MariaDB. Compare and contrast MySQL and MariaDB. Apr 26, 2025 am 12:08 AM

The main difference between MySQL and MariaDB is performance, functionality and license: 1. MySQL is developed by Oracle, and MariaDB is its fork. 2. MariaDB may perform better in high load environments. 3.MariaDB provides more storage engines and functions. 4.MySQL adopts a dual license, and MariaDB is completely open source. The existing infrastructure, performance requirements, functional requirements and license costs should be taken into account when choosing.

See all articles