SQL optimization and SQL Optimization Methods
- To optimize queries and avoid full table scanning, you should first consider creating an index on the columns involved in where and order.
- Try to avoid null value determination on the field in the where clause. Otherwise, the engine will discard the index and perform full table scan.
select id from t where num is null
It is best NOT to leave NULL for the database and try to use not null to fill the database.
Remarks, descriptions, comments, and so on can be set to NULL. Otherwise, it is best not to use NULL.
Do not think that NULL does not require space, for example, char (100) type. When a field is created, the space is fixed, regardless of whether or not the inserted value (NULL is also included ), all occupy 100 characters of space. If it is a variable-length field such as varchar, null does not occupy space.
You can set the default value 0 on num to make sure that the num column in the table does not have a null value, and then query it like this:
select id from t where num = 0
- Avoid using the where clause whenever possible! = Or <> operator. Otherwise, the engine will discard the index for full table scanning.
- Try to avoid using or in the where clause to connect conditions. If a field has an index and a field does not have an index, the engine will discard the index and perform a full table scan.
select id from t where num=10 or Name = 'admin'
You can query it as follows:
select id from t where num = 10union allselect id from t where Name = 'admin'
- Use in and not in with caution. Otherwise, full table scan may occur.
select id from t where num in(1,2,3)
For continuous values, you can use between instead of in:
select id from t where num between 1 and 3
In many cases, replacing in with exists is a good choice:
select num from a where num in(select num from b)
Replace the following statement:
select num from a where exists(select 1 from b where num=a.num)
- The following query will also cause a full table scan.
select id from t where name like ‘%abc%’
To improve efficiency, you can consider full-text search.
- If a parameter is used in the where clause, a full table scan is performed. Because SQL parses local variables only at runtime, the optimizer cannot postpone the selection of the access plan to runtime; it must be selected at compilation. However, if an access plan is created during compilation, the value of the variable is still unknown and thus cannot be used as an input for index selection. The following statement performs a full table scan:
select id from t where num = @num
You can change it to force query to use the index:
Select id from t with (index name) where num = @ num
- Avoid performing expression operations on fields in the where clause whenever possible, which will cause the engine to discard the use of indexes for full table scanning. For example:
select id from t where num/2 = 100
Should be changed:
select id from t where num = 100*2
- Avoid performing function operations on fields in the where clause whenever possible, which will cause the engine to discard the use of indexes for full table scanning. For example:
Select id from t where substring (name, 2005) = 'abc' -- idselect id starting with abc from t where datediff (day, createdate, '2017-11-30 ′) = 0 -- '2017-11-30 '-- generated id
Should be changed:
select id from t where name like 'abc%'select id from t where createdate >= '2005-11-30' and createdate < '2005-12-1'
- Do not perform functions, arithmetic operations, or other expression operations on the left side of "=" in the where clause. Otherwise, the system may not be able to correctly use the index.
- When using an index field as a condition, if the index is a composite index, you must use the first field in the index as the condition to ensure that the system uses the index, otherwise, the index will not be used, and the field order should be consistent with the index order as much as possible.
- Do not write meaningless queries. 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 any result set, but will consume system resources, should be changed to this:
create table #t(…)
- Update statement. If only one or two fields are modified, do not Update all fields. Otherwise, frequent calls may cause significant performance consumption and a large number of logs.
- For JOIN operations on tables with large data volumes (hundreds of rows are larger), you must perform the JOIN operation by page. Otherwise, the logical read operation will be high and the performance will be poor.
- Select count (*) from table; this way, the count without any conditions will cause a full table scan without any business significance, so it must be eliminated.
- The more the index is, the better it is. Although the index can improve the efficiency of the select statement, it also reduces the efficiency of insert and update, because the insert or update statements may recreate the index, therefore, you need to carefully consider how to create an index, depending on the actual situation. It is recommended that the number of indexes in a table be no more than 6. If there are too many indexes, consider whether the indexes on some columns that are not frequently used are necessary.
- Update the clustered index data column should be avoided as much as possible, because the order of the clustered index data column is the physical storage order of the table records. Once the column value changes, the order of the entire table record will be adjusted, it will consume a considerable amount of resources. If the application system needs to frequently update the clustered index data column, consider whether to create the index as a clustered index.
- Use numeric fields whenever possible. If fields containing only numerical information are not designed as numeric fields, this will reduce query and connection performance and increase storage overhead. This is because the engine compares each character in the string one by one during query and connection processing, and only one comparison is required for the number type.
- Try to use varchar/nvarchar instead of char/nchar, because the first step is to reduce the storage space of the variable-length field, which can save storage space. Secondly, for queries, searching in a relatively small field is obviously more efficient.
- Do not use select * from t anywhere, replace "*" with a specific field list, and do not return any fields that are not used.
- Try to use table variables instead of temporary tables. If the table variable contains a large amount of data, note that the index is very limited (only the primary key index ).
- Avoid frequent creation and deletion of temporary tables to reduce the consumption of system table resources. Temporary tables are not unavailable. Using them appropriately can make some routines more effective. For example, when you need to repeatedly reference a large table or a data set in a common table. However, it is best to use the export table for one-time events.
- When creating a temporary table, if a large amount of data is inserted at one time, you can use select into instead of create table to avoid creating a large number of logs to increase the speed. If the data volume is small, to ease system table resources, create table first and then insert.
- If a temporary table is used, you must explicitly delete all temporary tables at the end of the stored procedure. First truncate the table and then drop the table, so that the system table can be locked for a long time.
- Avoid using a cursor as much as possible because the efficiency of the cursor is poor. If the cursor operation has more than 10 thousand rows of data, you should consider rewriting.
- Before using the cursor-based or temporary table method, you should first find a set-based solution to solve the problem. The set-based method is generally more effective.
- Like a temporary table, a cursor is not unavailable. Using a FAST_FORWARD cursor for a small dataset is usually better than other row-by-row processing methods, especially when several tables must be referenced to obtain the required data. A routine that includes "sum" in the result set is usually faster than a cursor. If this is allowed during development, you can try both the cursor-based method and the set-based method to see which method works better.
- Set nocount on at the beginning of all stored procedures and triggers, and set nocount off at the end. You do not need to send the DONE_IN_PROC message to the client after executing each statement of the stored procedure and trigger.
- Avoid large transaction operations and improve system concurrency.
- Avoid returning large data volumes to the client whenever possible. If the data volume is too large, consider whether the appropriate requirements are reasonable.
Case studies: Split large DELETE or INSERT statements and submit SQL statements in batches
If you need to execute a large DELETE or INSERT query on an online website, you need to be very careful to avoid your operations to stop the entire website. Because these two operations lock the table, once the table is locked, other operations cannot be performed.
Apache has many sub-processes or threads. Therefore, it works very efficiently, and our server does not want to have too many sub-processes, threads, and database connections, which greatly occupy server resources, especially memory.
If you lock your table for a period of time, such as 30 seconds, for a site with high access traffic, the access process/thread and database link accumulated over the past 30 seconds, the number of opened files may not only cause your WEB service to crash, but also cause your entire server to crash immediately.
Therefore, if you have a large processing, you must split it. Using the LIMIT oracle (rownum) and SQL Server (top) conditions is a good method. The following is an example of mysql:
While (1) {// only 1000 pieces of mysql_query ("delete from logs where log_date <= '2017-11-01 'limit 2012"); if (mysql_affected_rows () = 0) {// deletion completed. Exit! Break;} // pause each time for a period of time. Release the table to allow access by other processes/threads. Usleep (50000 )}
I am the dividing line of tiantiao
Reference: http://www.cnblogs.com/yunfeifei/p/3850440.html
SQL statement Optimization
Because SQL optimization is complex and restricted by the Environment, you must follow the following principles to write SQL during development:
1. ORACLE uses the bottom-up sequence to parse the WHERE clause. According to this principle, the join between tables must be written before other WHERE conditions. The conditions that can filter out the maximum number of records must be written at the end of the WHERE clause.
For example:
(Inefficient)
SELECT... From emp e where sal> 50000 and job = 'manager' AND 25 <(select count (*) from emp where mgr = E. EMPNO );
(Efficient)
SELECT... From emp e where 25 <(select count (*) from emp where mgr = E. EMPNO) and sal> 50000 and job = 'manager ';
2. Avoid '*' in the SELECT clause '*'
When all columns are listed in the SELECT clause, it is convenient to reference '*' using dynamic SQL columns. however, this is a very inefficient method. in fact, ORACLE converts '*' into all column names in sequence during parsing. This task is done by querying the data dictionary, which means it takes more time.
3. Use the table Alias (Alias)
When connecting multiple tables in an SQL statement, use the table alias and prefix the alias on each Column. in this way, the parsing time can be reduced and the syntax errors caused by Column ambiguity can be reduced.
Note: Column ambiguity means that different SQL tables have the same Column name. When this Column appears in an SQL statement, the SQL parser cannot determine the attribute of this Column.
SQL Optimization
SELECT L_SUPPKEY, COUNT (1)
FROM LINEITEM
Group by L_SUPPKEY
UNION ALL
SELECT S_SUPPKEY, 0
FROM SUPPLIER
WHERE not exists ('x'
FROM LINEITEM
Where L_SUPPKEY = S_SUPPKEY );
Let me show you the link.