Home >Database >Mysql Tutorial >Use examples to tell you how to optimize SQL
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.
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.
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
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 Original execution time Original execution plan Initial optimization ideas
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 the execution plan after optimization
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!