Home Database Mysql Tutorial How to optimize sql statement?

How to optimize sql statement?

Apr 08, 2019 am 11:06 AM
sql optimization

Several methods for sql statement optimization include: 1. Unify the format of SQL statements; 2. Optimize queries and avoid full table scans; 3. SQL statements should be concise; 4. Consider using "temporary tables" to temporarily Store intermediate results; 5. Try to avoid large transaction operations; 6. Try to avoid returning large amounts of data to the client. The following article will introduce you to some details, I hope it will be helpful to you.

How to optimize sql statement?

In the early days of our development project, due to the relatively small amount of business data, the impact of the execution efficiency of some SQL on the program running efficiency was not obvious, and the development and operation and maintenance personnel It is also impossible to judge how efficient SQL is on the running efficiency of the program, so special optimization of SQL is rarely carried out. 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, optimization of SQL is necessary.

Several methods for sql statement optimization:

1. Unify the format of SQL statements

Many people think that the following two SQL statements are the same, but the database query optimizer thinks they are different.

select * from dual

select * From dual

Although the case is only different, the query analyzer It is considered that they are two different SQL statements and must be parsed twice. Generate 2 execution plans. Therefore, as a programmer, you should ensure that the same query statement is consistent everywhere, even one more space will not work!

2. Use * less , replace "*" with a specific field list, and do not return any unused fields.

3. To optimize the query, try to avoid full table scans

1) You should consider creating indexes on the columns involved in where and order by.

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:

select id from t where num is null
Copy after login

can be used on num Set the default value 0, make sure there is no null value in the num column in the table, and then query like this:

select id from t where num=0
Copy after login

3). Try to avoid using != or <> operators in the where clause, otherwise it will cause The engine gives up using the index and performs 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:

select id from t where num=10 or num=20
Copy after login

can be queried like this:

select id from t where num=10    
union all    
select id from t where num=20
Copy after login

5), use in and not in with caution, otherwise it will cause a full table scan, such as:

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

For continuous values, you can use between Don’t use in:

select id from t where num between 1 and 3
Copy after login

6), use like fuzzy query reasonably

Sometimes you need to perform some fuzzy query, such as:

select * from contact where username like ‘%yue%’
Copy after login

Keyword %yue%, Since "%" is used in front of yue, the query must scan the entire table. Unless necessary, do not add %

7 in front of the keywords. You should try to avoid expressing fields in the where clause. This will cause the engine to give up using the index and perform a full table scan. For example:

select id from t where num/2=100
Copy after login

should be changed to:

select id from t where num=100*2
Copy after login

8), you should 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:

Query the ID whose name starts with abc

select id from t where substring(name,1,3)=&#39;abc&#39;
Copy after login

should be changed to:

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

4. Use exists instead of in

Many times it is a good choice to use exists instead of in. Exists only checks existence and its performance is much better than in. Example:

select num from a where num in(select num from b)
Copy after login

Replace with the following statement:

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

5. Don’t write SQL statements that are too long, too redundant, and be concise; if you can use one sentence, don’t Use two sentences

Generally, the results of a Select statement are used as a subset, and then the query is performed from the subset. This kind of nested statement is relatively common, but according to experience, more than With three levels of nesting, the query optimizer can easily give wrong execution plans. Because it was stunned. Things like artificial intelligence are ultimately inferior to human resolution. If people are dizzy, I can guarantee that the database will be dizzy as well.

In addition, the execution plan can be reused. The simpler the SQL statement, the higher the possibility of being reused. As long as one character changes in a complex SQL statement, it must be re-parsed, and then a lot of garbage will be stuffed in the memory. It is conceivable how inefficient the database will be.

6. Consider using a "temporary table" to temporarily store intermediate results

An important way to simplify SQL statements is to use a temporary table to temporarily store intermediate results. However, the temporary table The benefits are far more than these. The temporary results are temporarily stored in the temporary table, and subsequent queries are in tempdb. This can avoid multiple scans of the main table in the program, and also greatly reduces the "shared lock" blocking "update lock" during program execution. , reducing blocking and improving concurrency performance.

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

8. 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 only one comparison is enough for numeric types.

9. 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.​

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

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

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

13. 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.

Recommended video tutorials: "

MySQL Tutorial"

The above is the entire content of this article, I hope it will be helpful to everyone's learning. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !

The above is the detailed content of How to optimize sql statement?. 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 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)

What is the difference between HQL and SQL in Hibernate framework? What is the difference between HQL and SQL in Hibernate framework? Apr 17, 2024 pm 02:57 PM

HQL and SQL are compared in the Hibernate framework: HQL (1. Object-oriented syntax, 2. Database-independent queries, 3. Type safety), while SQL directly operates the database (1. Database-independent standards, 2. Complex executable queries and data manipulation).

Comparison and differences of SQL syntax between Oracle and DB2 Comparison and differences of SQL syntax between Oracle and DB2 Mar 11, 2024 pm 12:09 PM

Oracle and DB2 are two commonly used relational database management systems, each of which has its own unique SQL syntax and characteristics. This article will compare and differ between the SQL syntax of Oracle and DB2, and provide specific code examples. Database connection In Oracle, use the following statement to connect to the database: CONNECTusername/password@database. In DB2, the statement to connect to the database is as follows: CONNECTTOdataba

C++ program optimization: time complexity reduction techniques C++ program optimization: time complexity reduction techniques Jun 01, 2024 am 11:19 AM

Time complexity measures the execution time of an algorithm relative to the size of the input. Tips for reducing the time complexity of C++ programs include: choosing appropriate containers (such as vector, list) to optimize data storage and management. Utilize efficient algorithms such as quick sort to reduce computation time. Eliminate multiple operations to reduce double counting. Use conditional branches to avoid unnecessary calculations. Optimize linear search by using faster algorithms such as binary search.

Analysis of the impact of MySQL connection number on database performance Analysis of the impact of MySQL connection number on database performance Mar 16, 2024 am 10:09 AM

Analysis of the Impact of MySQL Connection Number on Database Performance With the continuous development of Internet applications, databases have become an important data storage and management tool to support application systems. In the database system, the number of connections is an important concept, which is directly related to the performance and stability of the database system. This article will start from the perspective of MySQL database, explore the impact of the number of connections on database performance, and analyze it through specific code examples. 1. What is the number of connections? The number of connections refers to the number of client connections supported by the database system at the same time. It can also be managed

How to optimize the startup items of WIN7 system How to optimize the startup items of WIN7 system Mar 26, 2024 pm 06:20 PM

1. Press the key combination (win key + R) on the desktop to open the run window, then enter [regedit] and press Enter to confirm. 2. After opening the Registry Editor, we click to expand [HKEY_CURRENT_USERSoftwareMicrosoftWindowsCurrentVersionExplorer], and then see if there is a Serialize item in the directory. If not, we can right-click Explorer, create a new item, and name it Serialize. 3. Then click Serialize, then right-click the blank space in the right pane, create a new DWORD (32) bit value, and name it Star

Vivox100s parameter configuration revealed: How to optimize processor performance? Vivox100s parameter configuration revealed: How to optimize processor performance? Mar 24, 2024 am 10:27 AM

Vivox100s parameter configuration revealed: How to optimize processor performance? In today's era of rapid technological development, smartphones have become an indispensable part of our daily lives. As an important part of a smartphone, the performance optimization of the processor is directly related to the user experience of the mobile phone. As a high-profile smartphone, Vivox100s's parameter configuration has attracted much attention, especially the optimization of processor performance has attracted much attention from users. As the &quot;brain&quot; of the mobile phone, the processor directly affects the running speed of the mobile phone.

What are some ways to resolve inefficiencies in PHP functions? What are some ways to resolve inefficiencies in PHP functions? May 02, 2024 pm 01:48 PM

Five ways to optimize PHP function efficiency: avoid unnecessary copying of variables. Use references to avoid variable copying. Avoid repeated function calls. Inline simple functions. Optimizing loops using arrays.

'Black Myth: Wukong ' Xbox version was delayed due to 'memory leak', PS5 version optimization is in progress 'Black Myth: Wukong ' Xbox version was delayed due to 'memory leak', PS5 version optimization is in progress Aug 27, 2024 pm 03:38 PM

Recently, "Black Myth: Wukong" has attracted huge attention around the world. The number of people online at the same time on each platform has reached a new high. This game has achieved great commercial success on multiple platforms. The Xbox version of "Black Myth: Wukong" has been postponed. Although "Black Myth: Wukong" has been released on PC and PS5 platforms, there has been no definite news about its Xbox version. It is understood that the official has confirmed that "Black Myth: Wukong" will be launched on the Xbox platform. However, the specific launch date has not yet been announced. It was recently reported that the Xbox version's delay was due to technical issues. According to a relevant blogger, he learned from communications with developers and "Xbox insiders" during Gamescom that the Xbox version of "Black Myth: Wukong" exists.

See all articles