Although hardware costs have dropped nowadays, improving system performance by upgrading hardware is also a common optimization method. Systems with high real-time requirements still need to be optimized from the SQL aspect. Today we will introduce how to optimize SQL based on examples.
Judge the problem SQL
When you judge whether there is a problem with SQL, you can judge it through two phenomena:
-
System level phenomenon
CPU consumption is serious
IO waiting is serious
The page response time is too long
-
Timeout and other errors appear in the application log
You can use the sar command and the top command to view the current system status. You can also observe the system status through monitoring tools such as Prometheus and Grafana.
- ##SQL statement appearance
- Lengthy
- Execution The time is too long
- Getting data from full table scan
- The rows and cost in the execution plan are very large
- MySQL
- Slow query log
- Test tool loadrunner
- Percona's ptquery and other tools
- Oracle
- AWR report
- Test tool loadrunner etc.
- Related internal views such as v$, $session_wait, etc.
- GRID CONTROL monitoring tool
- Dameng database
- AWR report
- Test tool loadrunner etc.
- Dameng performance monitoring tool (dem)
- Related internal views such as v$, $session_wait, etc.
If there are few indexes, the query will be slow; if there are too many indexes, it will take up a lot of space, and when executing add, delete, or modify statements, The index needs to be maintained dynamically, which affects performance. If the selection rate is high (fewer duplicate values) and is frequently referenced by where, a B-tree index needs to be established; Generally, join columns need to be indexed; it is more efficient to use full-text index for complex document type queries; The establishment of indexes should strike a balance between query and DML performance; when creating composite indexes, attention should be paid to queries based on non-leading columns• Use UNION ALL instead of UNION
UNION ALL has higher execution efficiency than UNION. UNION needs to be deduplicated when executed; UNION needs to sort data• Avoid select * writing
Optimize when executing SQL The processor needs to convert * into specific columns; each query must return the table, and covering indexes cannot be used.• It is recommended to create an index for JOIN fields
Generally, JOIN fields are indexed in advance• Avoid complex SQL statements
Improve readability; avoid the probability of slow queries; can be converted into multiple short queries and processed by the business end• Avoid where 1=1 writing • Avoid order by rand() similar writing style
RAND() causing the data column to be scanned multiple timesSQL optimizationExecution plan
Be sure to read the execution plan before completing SQL optimization. The execution plan will tell you where the efficiency is low and where optimization is needed. Let's take MYSQL as an example to see what the execution plan is. (The execution plan of each database is different and you need to understand it yourself)
Field | Explanation |
---|---|
Each is executed independently The operation identifier identifies the order in which the object is operated. The larger the id value, the first to be executed. If they are the same, the execution order is from top to bottom | |
In query The type of each select clause | |
The name of the object being operated on, usually the table name, but there are other formats | |
Matching partition information (value is NULL for non-partitioned tables) | |
Type of join operation | |
Possibly used indexes | |
The index actually used by the optimizer (the most important column) The join types from best to worst are const, eq_reg, ref, range, index and ALL. When ALL appears, it means that the current SQL has a "bad smell" | |
The length of the index key selected by the optimizer, in bytes | |
indicates the reference object of the operated object in this row. No reference object is NULL | |
Query The number of tuples scanned by the execution (for innodb, this value is an estimate) | |
Percentage of the number of tuples on the conditional table that is filtered | |
Important supplementary information of the execution plan, be careful when the words Using filesort, Using temporary appear in this column, it is likely that the SQL statement needs to be optimized |
CREATE TABLE `a` ( `id` int(11) NOT NULLAUTO_INCREMENT, `seller_id` bigint(20) DEFAULT NULL, `seller_name` varchar(100) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL, `gmt_create` varchar(30) DEFAULT NULL, PRIMARY KEY (`id`) ); CREATE TABLE `b` ( `id` int(11) NOT NULLAUTO_INCREMENT, `seller_name` varchar(100) DEFAULT NULL, `user_id` varchar(50) DEFAULT NULL, `user_name` varchar(100) DEFAULT NULL, `sales` bigint(20) DEFAULT NULL, `gmt_create` varchar(30) DEFAULT NULL, PRIMARY KEY (`id`) ); CREATE TABLE `c` ( `id` int(11) NOT NULLAUTO_INCREMENT, `user_id` varchar(50) DEFAULT NULL, `order_id` varchar(100) DEFAULT NULL, `state` bigint(20) DEFAULT NULL, `gmt_create` varchar(30) DEFAULT NULL, PRIMARY KEY (`id`) );Three tables are related to query the order status of the current user 10 hours before and after the current time, and sort them in ascending order according to the order creation time. The specific SQL is as follows
select a.seller_id, a.seller_name, b.user_name, c.state from a, b, c where a.seller_name = b.seller_name and b.user_id = c.user_id and c.user_id = 17 and a.gmt_create BETWEEN DATE_ADD(NOW(), INTERVAL – 600 MINUTE) AND DATE_ADD(NOW(), INTERVAL 600 MINUTE) order by a.gmt_create;View data volume
- The where condition field type in SQL must be consistent with the table structure. The user_id in the table is varchar( 50) type, the actual int type used in SQL, there is implicit conversion, and no index is added. Change the user_id field in tables b and c to int type.
- Because there is an association between table b and table c, create an index on the user_id of table b and table c
- Because there is an association between table a and table b, Create an index on the seller_name field of tables a and b
- Use composite index to eliminate temporary tables and sort
alter table b modify `user_id` int(10) DEFAULT NULL; alter table c modify `user_id` int(10) DEFAULT NULL; alter table c add index `idx_user_id`(`user_id`); alter table b add index `idx_user_id_sell_name`(`user_id`,`seller_name`); alter table a add index `idx_sellname_gmt_sellid`(`gmt_create`,`seller_name`,`seller_id`);View the execution time after optimization
- View execution plan explain
- If there is an alarm message, check the alarm message show warnings;
- View the table structure and index information involved in SQL
- Think about possible optimization points according to the execution plan
- Perform table structure changes, add indexes, SQL rewrite and other operations according to possible optimization points
- View the optimized execution time and execution plan
- If the optimization effect is not obvious, repeat the fourth step
mysql tutorial"
The above is the detailed content of Use examples to tell you how to optimize SQL. For more information, please follow other related articles on the PHP Chinese website!

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

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.

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools