Home Database SQL What are the commonly used methods for sql optimization?

What are the commonly used methods for sql optimization?

Aug 24, 2020 pm 01:12 PM
sql optimization

Commonly used methods for sql optimization are: 1. Try to avoid full table scans, and consider establishing indexes on the columns involved in where and order by; 2. Try to avoid null values ​​for fields in the where clause. Judgment; 3. Use in and not in with caution; 4. Try to avoid large transaction operations and improve system concurrency.

What are the commonly used methods for sql optimization?

1. Why should we optimize SQL

In the early days of our development project, due to the business data The amount of SQL is relatively small, and the impact of the execution efficiency of some SQL on the running efficiency of the program is not obvious, and development and operation and maintenance personnel cannot judge how efficient SQL is on the running efficiency of the program. Therefore, special optimization of SQL is rarely carried out, and as a result, SQL is rarely optimized. As time accumulates and the amount of business data increases, the impact of SQL execution efficiency on the running efficiency of the program gradually increases. At this time, it is necessary to optimize SQL.

2. Some common methods of SQL optimization

1. To optimize the query, you should try to avoid full table scans. First, you should consider where and order by. Create an index on the column.

2. Try to avoid making null value judgments on fields in the where clause, otherwise the engine will give up using the index and perform a full table scan, such as:

1

select id from t where num is null

Copy after login

can be set on num The default value is 0. Make sure there is no null value in the num column in the table, and then query like this:

1

select id from t where num=0

Copy after login

3. Try to avoid using the != or <> operator in the where clause, otherwise the engine will be abandoned. Index and perform a full table scan.

4. Try to avoid using or in the where clause to connect conditions, otherwise the engine will give up using the index and perform a full table scan, such as:

1

select id from t where num=10 or num=20

Copy after login

You can query like this:

1

2

3

select id from t where num=10   

union all   

select id from t where num=20

Copy after login

5.in and not in should also be used with caution, otherwise it will lead to a full table scan, such as:

1

select id from t where num in(1,2,3)

Copy after login

For continuous values, if you can use between, do not use in :

1

select id from t where num between 1 and 3

Copy after login

6. The following query will also result in a full table scan:

1

select id from t where name like &#39;%abc%&#39;

Copy after login

7. You should try to avoid expression operations on fields in the where clause, which will Causes the engine to give up using the index and perform a full table scan. For example:

1

select id from t where num/2=100

Copy after login

should be changed to:

1

select id from t where num=100*2

Copy after login

8. Try to avoid performing functional operations on fields in the where clause, which will cause the engine to give up using the index and Perform a full table scan. For example:

1

select id from t where substring(name,1,3)=&#39;abc&#39;--name以abc开头的id

Copy after login

should be changed to:

1

select id from t where name like &#39;abc%&#39;

Copy after login

9. Do not perform functions, arithmetic operations or other expression operations on the left side of "=" in the where clause, otherwise the system will Indexes may not be used correctly.

10. When using an index field as a condition, if the index is a composite index, the first field in the index must be used as the condition to ensure that the system uses the index, otherwise the index will not will be used, and the field order should be consistent with the index order as much as possible.

11. Do not write meaningless queries. For example, if you need to generate an empty table structure:

1

select col1,col2 into #t from t where 1=0

Copy after login

This type of code will not return any result set, but it will consume system resources and should be changed. Like this:

1

create table #t(...)

Copy after login

12. Many times it is a good choice to use exists instead of in:

1

select num from a where num in(select num from b)

Copy after login

Replace with the following statement:

1

select num from a where exists(select 1 from b where num=a.num)

Copy after login

13. Not all indexes It is valid for all queries. SQL optimizes queries based on the data in the table. When there is a large amount of duplicate data in the index column, the SQL query may not use the index. For example, if there is a field sex in a table, almost half of it is male and half of female. Then Even if an index is built on sex, it will not affect query efficiency.

14. The more indexes, the better. Although the index can improve the efficiency of the corresponding select, it also reduces the efficiency of insert and update.

Because it is possible to insert or update The index will be rebuilt, so how to build the index needs to be carefully considered and depends on the specific situation.​

It is best not to have more than 6 indexes on a table. If there are too many, you should consider whether it is necessary to build indexes on some columns that are not commonly used.​

15. Try to use numeric fields. If the fields contain only numerical information, try not to design them as character fields. This will reduce the performance of query and connection, and increase storage overhead.

This is because the engine will compare each character in the string one by one when processing queries and connections, and for numeric types, only one comparison is enough.

16. Use varchar instead of char as much as possible, because first of all, variable length fields have small storage space and can save storage space.

Secondly, for queries, in a relatively small field The search efficiency is obviously higher.

17. Do not use select * from t anywhere, replace "*" with a specific field list, and do not return any unused fields.​

18. Avoid frequently creating and deleting temporary tables to reduce the consumption of system table resources.

19. Temporary tables are not unusable, and using them appropriately can make certain routines more efficient, for example, when you need to repeatedly reference a certain data set in a large table or a commonly used table. However, for one-off events, it's better to use an export table.

20. When creating a temporary table, if the amount of data inserted at one time is large, you can use select into instead of create table to avoid causing a large number of logs,

to improve the speed; if the amount of data Not big. In order to alleviate the resources of the system table, you should first create the table and then insert.

21. If temporary tables are used, all temporary tables must be explicitly deleted at the end of the stored procedure, first truncate table, and then drop table. This can avoid long-term locking of system tables.

22. Try to avoid using cursors, because cursors are less efficient. If the data operated by the cursor exceeds 10,000 rows, then you should consider rewriting.​

23. Before using the cursor-based method or the temporary table method, you should first look for a set-based solution to solve the problem. The set-based method is usually more effective.

24. Like temporary tables, cursors are not unusable. Using FAST_FORWARD cursors with small data sets is often better than other row-by-row processing methods, especially when several tables must be referenced to obtain the required data.

Routines that include a "total" in the result set are usually faster than using a cursor. If development time permits, you can try both the cursor-based method and the set-based method to see which method works better.

25. Try to avoid large transaction operations and improve system concurrency.

26. Try to avoid returning large amounts of data to the client. If the amount of data is too large, you should consider whether the corresponding requirements are reasonable.

Related recommendations: "PHP Tutorial", "mysql Tutorial"

The above is the detailed content of What are the commonly used methods for sql optimization?. 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months 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)

How to optimize Discuz forum performance? How to optimize Discuz forum performance? Mar 12, 2024 pm 06:48 PM

How to optimize Discuz forum performance? Introduction: Discuz is a commonly used forum system, but it may encounter performance bottlenecks during use. In order to improve the performance of Discuz Forum, we can optimize it from many aspects, including database optimization, cache settings, code adjustment, etc. The following will introduce how to optimize the performance of the Discuz forum through specific operations and code examples. 1. Database optimization: Index optimization: Creating indexes for frequently used query fields can greatly improve query speed. For example

How to optimize the performance of SQL Server and MySQL so that they can perform at their best? How to optimize the performance of SQL Server and MySQL so that they can perform at their best? Sep 11, 2023 pm 01:40 PM

How to optimize the performance of SQLServer and MySQL so that they can perform at their best? Abstract: In today's database applications, SQLServer and MySQL are the two most common and popular relational database management systems (RDBMS). As the amount of data increases and business needs continue to change, optimizing database performance has become particularly important. This article will introduce some common methods and techniques for optimizing the performance of SQLServer and MySQL to help users take advantage of

Linux performance tuning~ Linux performance tuning~ Feb 12, 2024 pm 03:30 PM

The Linux operating system is an open source product, and it is also a practice and application platform for open source software. Under this platform, there are countless open source software supports, such as apache, tomcat, mysql, php, etc. The biggest concept of open source software is freedom and openness. Therefore, as an open source platform, Linux's goal is to achieve optimal application performance at the lowest cost through the support of these open source software. When it comes to performance issues, what is mainly achieved is the best combination of the Linux operating system and applications. 1. Overview of performance issues System performance refers to the effectiveness, stability and response speed of the operating system in completing tasks. Linux system administrators may often encounter problems such as system instability and slow response speed, such as

Core differences between Sybase and Oracle database management systems Core differences between Sybase and Oracle database management systems Mar 08, 2024 pm 05:54 PM

The core differences between Sybase and Oracle database management systems require specific code examples. Database management systems play a vital role in the field of modern information technology. As two well-known relational database management systems, Sybase and Oracle occupy an important position in the database field. important position. Although they are both relational database management systems, there are some core differences in practical applications. This article will compare Sybase and Oracle from multiple perspectives, including architecture, syntax, performance, etc.

What does any mean in sql What does any mean in sql May 01, 2024 pm 11:03 PM

The ANY keyword in SQL is used to check whether a subquery returns any rows that satisfy a given condition: Syntax: ANY (subquery) Usage: Used with comparison operators, if the subquery returns any rows that satisfy the condition, the ANY expression Evaluates to true Advantages: simplifies queries, improves efficiency, and is suitable for processing large amounts of data Limitations: does not provide specific rows that meet the condition, if the subquery returns multiple rows that meet the condition, only true is returned

SQL Server and MySQL performance tuning: Best practices and key tips. SQL Server and MySQL performance tuning: Best practices and key tips. Sep 11, 2023 pm 12:46 PM

SQLServer and MySQL Performance Tuning: Best Practices and Key Tips Summary: This article will introduce the performance tuning methods of two common relational database systems, SQLServer and MySQL, and provide some best practices and key tips to help developers and Database administrators improve the performance and efficiency of database systems. Introduction: In modern application development, database systems are an indispensable part. As the amount of data increases and user demands increase, the optimization of database performance becomes particularly important. SQ

MySql SQL statement execution plan: How to optimize the MySQL query process MySql SQL statement execution plan: How to optimize the MySQL query process Jun 16, 2023 am 09:15 AM

With the rapid development of the Internet, data storage and processing are becoming more and more important. Therefore, relational databases are an integral part of modern software platforms. MySQL database has become one of the most popular relational databases because it is simple to use, easy to deploy and manage. However, MySQL database performance issues often become an issue when dealing with large amounts of data. In this article, we will delve into MySQL's SQL statement execution plan and introduce how to improve MySQL data by optimizing the query process.

How to achieve low-level optimization of MySQL: tips and best practices for advanced optimization of SQL statements How to achieve low-level optimization of MySQL: tips and best practices for advanced optimization of SQL statements Nov 08, 2023 pm 04:32 PM

MySQL is a widely used relational database management system commonly used for web application development and data storage. In practical applications, the underlying optimization of MySQL is particularly important, among which the advanced optimization of SQL statements is the key to improving database performance. This article will introduce some tips and best practices for implementing MySQL's underlying optimization, as well as specific code examples. Determine the query conditions When writing SQL statements, you must first clearly define the query conditions and avoid using unlimited wildcard queries, that is, avoid using "%" to open the query.

See all articles