Introduction to SQL statement optimization strategies
1. Avoid full table scan
To optimize the query, try to avoid full table scan. First, consider where and order by Create an index on the involved columns.
2. Avoid judging null values
You should try to avoid judging null values for fields in the where clause, otherwise the engine will give up using the index and perform the entire table Scan, such as:
select id from t where num is null
You can set the default value 0 on num, ensure that there is no null value in the num column in the table, and then query like this:
select id from t where num=0
(free learning video tutorial recommendation: mysql video tutorial)
3. Avoid unequal value judgment
You should try to avoid using it in the where clause != or operator, otherwise the engine will give up using the index and perform a full table scan.
4. Avoid using or logic
You should try to avoid using or in the where clause to connect conditions, otherwise it will cause The engine gives up using the index and performs a full table scan, such as:
select id from t where num=10 or num=20
You can query like this:
select id from t where num=10 union all select id from t where num=20
5. Use in and not in logic with caution
in and not in should also be used with caution, otherwise it will cause a full table scan, such as:
select id from t1 where num in(select id from t2 where id > 10)
At this time, the outer query will scan the entire table without using the index. It can be modified to:
select id from t1,(select id from t1 where id > 10)t2 where t1.id = t2.id
At this time, the index is used, which can significantly improve query efficiency.
6. Pay attention to fuzzy query
The following query will also cause a full table scan:
select id from t where name like '%abc%'
If fuzzy query is a necessary condition, you can use it Select id from t where name like 'abc%' to implement fuzzy query, in which case the index will be used. If header matching is necessary logic, it is recommended to use a full-text search engine (Elastic search, Lucene, Solr, etc.).
7. Avoid field calculations in query conditions
You should try to avoid expression operations on fields in the where clause, which will cause the engine to give up using the index. Full table scan. For example:
select id from t where num/2=100
should be changed to:
select id from t where num=100*2
8. Avoid performing function operations on fields in query conditions
Should try to avoid using the where clause Function operations are performed on fields in the field, which will cause the engine to give up using the index and perform a full table scan. For example:
select id from t where substring(name,1,3)='abc'--name 以abc 开头的id
should be changed to:
select id from t where name like 'abc%'
9. Pay attention to the
on the left side of the WHERE clause "=" and do not use it in the where clause. Do not perform functions, arithmetic operations or other expression operations on the left side of "=" in the sentence, otherwise the system may not be able to use the index correctly.
10. Use of composite index
When using an index field as a condition, if the index is a composite index, the first field in the index must be used Only when used as a condition can the system use the index, otherwise the index will not be used, and the field order should be consistent with the index order as much as possible.
11. Do not define unobjectionable queries.
Do not write meaningless queries. For example, if you need to generate an empty table structure:
select col1,col2 into #t from t where 1=0
This type of code will not return anything. The result set, but it will consume system resources, should be changed to this:
create table #t(...)
12. exists
In many cases, it is a good idea to use exists instead of in. Select:
select num from a where num in(select num from b)
Replace with the following statement:
select num from a where exists(select 1 from b where num=a.num)
13. The index may also fail
并不是所有索引对查询都有效,SQL 是根据表中数据来进行查询优化的,当索引列有大量数据重复时,SQL 查询可能不会去利用索引,如一表中有字段sex,male、female 几乎各一半,那么即使在sex 上建了索引也对查询效率起不了作用。
14、表格字段类型选择
尽量使用数字型字段,若只含数值信息的字段尽量不要设计为字符型,这会降低查询和连接的性能,并会增加存储开销。
这是因为引擎在处理查询和连接时会逐个比较字符串中每一个字符,而对于数字型而言只需要比较一次就够了。尽可能的使用varchar 代替char ,因为首先可变长度字段存储空间小,可以节省存储空间,其次对于查询来说,在一个相对较小的字段内搜索效率显然要高些。
15、查询语法中的字段
任何地方都不要使用select * from t ,用具体的字段列表代替“*”,不要返回用不到的任何字段。
16、索引无关优化
不使用*、尽量不使用union,union all 等关键字、尽量不使用or 关键字、尽量使用等值判断。表连接建议不超过5 个。如果超过5 个,则考虑表格的设计。(互联网应用中)表连接方式使用外联优于内联。外连接有基础数据存在。
如:A left join B,基础数据是A。A inner join B,没有基础数据的,先使用笛卡尔积完成全连接,在根据连接条件得到内连接结果集。
大数据量级的表格做分页查询时,如果页码数量过大,则使用子查询配合完成分页逻辑。
Select * from table limit 1000000, 10 Select * from table where id in (select pk from table limit100000, 10)
相关文章教程推荐:mysql教程
The above is the detailed content of Introduction to SQL statement optimization strategies. For more information, please follow other related articles on the PHP Chinese website!

InnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.

Key metrics for EXPLAIN commands include type, key, rows, and Extra. 1) The type reflects the access type of the query. The higher the value, the higher the efficiency, such as const is better than ALL. 2) The key displays the index used, and NULL indicates no index. 3) rows estimates the number of scanned rows, affecting query performance. 4) Extra provides additional information, such as Usingfilesort prompts that it needs to be optimized.

Usingtemporary indicates that the need to create temporary tables in MySQL queries, which are commonly found in ORDERBY using DISTINCT, GROUPBY, or non-indexed columns. You can avoid the occurrence of indexes and rewrite queries and improve query performance. Specifically, when Usingtemporary appears in EXPLAIN output, it means that MySQL needs to create temporary tables to handle queries. This usually occurs when: 1) deduplication or grouping when using DISTINCT or GROUPBY; 2) sort when ORDERBY contains non-index columns; 3) use complex subquery or join operations. Optimization methods include: 1) ORDERBY and GROUPB

MySQL/InnoDB supports four transaction isolation levels: ReadUncommitted, ReadCommitted, RepeatableRead and Serializable. 1.ReadUncommitted allows reading of uncommitted data, which may cause dirty reading. 2. ReadCommitted avoids dirty reading, but non-repeatable reading may occur. 3.RepeatableRead is the default level, avoiding dirty reading and non-repeatable reading, but phantom reading may occur. 4. Serializable avoids all concurrency problems but reduces concurrency. Choosing the appropriate isolation level requires balancing data consistency and performance requirements.

MySQL is suitable for web applications and content management systems and is popular for its open source, high performance and ease of use. 1) Compared with PostgreSQL, MySQL performs better in simple queries and high concurrent read operations. 2) Compared with Oracle, MySQL is more popular among small and medium-sized enterprises because of its open source and low cost. 3) Compared with Microsoft SQL Server, MySQL is more suitable for cross-platform applications. 4) Unlike MongoDB, MySQL is more suitable for structured data and transaction processing.

MySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.

The MySQL learning path includes basic knowledge, core concepts, usage examples, and optimization techniques. 1) Understand basic concepts such as tables, rows, columns, and SQL queries. 2) Learn the definition, working principles and advantages of MySQL. 3) Master basic CRUD operations and advanced usage, such as indexes and stored procedures. 4) Familiar with common error debugging and performance optimization suggestions, such as rational use of indexes and optimization queries. Through these steps, you will have a full grasp of the use and optimization of MySQL.

MySQL's real-world applications include basic database design and complex query optimization. 1) Basic usage: used to store and manage user data, such as inserting, querying, updating and deleting user information. 2) Advanced usage: Handle complex business logic, such as order and inventory management of e-commerce platforms. 3) Performance optimization: Improve performance by rationally using indexes, partition tables and query caches.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver CS6
Visual web development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.