Tips for optimizing several SQL statement commands

Source: Internet
Author: User
Tags getdate regular expression

1. In applications, ensure that the number of accesses to the database is minimized on the basis of implementing functions;
Search for parameters to minimize the number of rows accessed to the table and minimize the result set, thus reducing the network burden.
Open operations should be processed separately as much as possible to improve the response speed each time; when using SQL in the data window, try to make
The indexes used are placed in the first selected column. The algorithm structure should be as simple as possible. During queries, do not use wildcard too much.
For example, SELECT * FROM T1 statement, SELECT several columns for which to use: SELECT COL1, COL2 FROM
T1; if possible, try to limit the number of rows in the result set as much as possible, for example: select top 300
COL1, COL2, COL3 FROM T1, because in some cases the user does not need so much data. Do not
Using database cursors in applications is a very useful tool, but it is more useful than using conventional, set-oriented SQL statements.
Statement requires more overhead; extract data searches in a specific order.

2. Avoid using incompatible data types. Such as float and int, char and varchar, binary, and
Varbinary is incompatible. Incompatible data types may make the optimizer unable to execute some operations that can be imported
. For example:
SELECT name FROM employee WHERE salary> 60000
In this statement, if the salary field is of the money type, it is difficult for the optimizer to optimize it because 60000
It is an integer. We should convert the integer type into a coin type during programming, instead of waiting for the conversion at runtime.

3. Avoid performing function or expression operations on fields in the WHERE clause whenever possible, which will cause the engine to abandon
Use indexes to scan the entire table. For example:
SELECT * FROM T1 WHERE F1/2 = 100
Should be changed:
SELECT * FROM T1 WHERE F1 = 100*2

SELECT * from record where substring (CARD_NO, 5378) = '20140901'
Should be changed:
SELECT * from record where CARD_NO LIKE '201312'

SELECT member_number, first_name, last_name FROM members
Where datediff (yy, datofbirth, GETDATE ()> 21
Should be changed:
SELECT member_number, first_name, last_name FROM members
WHERE dateofbirth <DATEADD (yy,-21, GETDATE ())
That is, any column operation will cause table scanning, including database functions, computing expressions, and so on.
If possible, move the operation to the right of the equal sign.

4. Avoid using it! = Or <>, is null, is not null, IN, not in, and so on,
Because this will make the system unable to use the index, but can only directly search the data in the table. For example:
SELECT id FROM employee WHERE id! = 'B %'
The Optimizer cannot use indexes to determine the number of rows to be hit. Therefore, you need to search all rows in the table.
 
5. Use numeric fields as much as possible. Some developers and database administrators prefer to include value-based messages.
Information Field
Designed to be optimized, this reduces query and connection performance and increases storage overhead. This is because the engine
Process the query and connect back to compare each character in the string one by one, but for the number type, you only need to compare one
This is enough.

6. Use the EXISTS and not exists clauses reasonably. As follows:
1. select sum (T1.C1) FROM T1 WHERE (
(Select count (*) FROM T2 WHERE T2.C2 = T1.C2> 0)
2. select sum (T1.C1) FROM T1WHERE EXISTS (
SELECT * FROM T2 WHERE T2.C2 = T1.C2)
The two produce the same results, but the latter is obviously more efficient than the former. Because the latter will not generate a large number of locks
Fixed table or index scan.
If you want to check whether a record exists in the table, do not use count (*) as inefficient and waste the server
Server resources. It can be replaced by EXISTS. For example:
IF (select count (*) FROM table_name WHERE column_name = 'XXX ')
Can be written:
If exists (SELECT * FROM table_name WHERE column_name = 'XXX ')

You often need to write a T_ SQL statement to compare a parent result set and a child result set to find whether the statement exists in the parent
Records in the result set but not in the subresult set, such:
1. SELECT a. hdr_key FROM hdr_tbl a ---- tbl a indicates that tbl is replaced by alias.
Where not exists (SELECT * FROM dtl_tbl B WHERE a. hdr_key = B. hdr_key)

2. SELECT a. hdr_key FROM hdr_tbl
Left join dtl_tbl B ON a. hdr_key = B. hdr_key WHERE B. hdr_key IS NULL

3. SELECT hdr_key FROM hdr_tbl
WHERE hdr_key not in (SELECT hdr_key FROM dtl_tbl)
The three writing methods can get the same correct results, but the efficiency is reduced in turn.

7. Try to avoid using non-start letters to search for indexed character data. This also makes the engine unable
Use indexes.
See the following example:
SELECT * FROM T1 where name like '% L %'
SELECT * FROM T1 where substing (NAME, 2, 1) = 'l'
SELECT * FROM T1 where name like 'L %'
Even if the NAME field has an index, the first two queries still cannot be accelerated using the index, and the engine has
Perform operations on all data in the entire table one by one. The third query can use indexes to speed up operations.

8. There may be more than one connection condition between two tables by using the connection condition.
Write the complete connection conditions in the WHERE clause, which may greatly improve the query speed.
Example:
Select sum (A. AMOUNT) from account a, card B where a. CARD_NO = B. CARD_NO
Select sum (A. AMOUNT) from account a, card B where a. CARD_NO = B. CARD_NO
And a. ACCOUNT_NO = B. ACCOUNT_NO
The second statement is much faster than the first statement.

9. Eliminates sequential access to data in large table rows
Although all check columns have indexes, some forms of WHERE clauses force the optimizer to use
Sequential access. For example:
SELECT * FROM orders WHERE (customer_num = 104 AND order_num> 1001) OR
Order_num= 1008
The solution can be to use the union to avoid sequential access:
SELECT * FROM orders WHERE customer_num = 104 AND order_num> 1001
UNION
SELECT * FROM orders WHERE order_num = 1008
In this way, you can use the index path to process queries.

10. Avoid difficult regular expressions
The LIKE keyword supports wildcard matching, technically called a regular expression. However, this matching is especially time-consuming.
. Example: SELECT * FROM customer WHERE zipcode LIKE "98 ___"
Even if an index is created on the zipcode field, sequential scanning is used in this case. For example
If you change the statement to SELECT * FROM customer WHERE zipcode> "98000",
The index will be used for query, which obviously greatly improves the speed.
11. Use view to accelerate query
Sort a subset of a table and create a view, which sometimes accelerates query. It helps avoid multiple sorting
In addition, the optimizer can be simplified in other aspects. For example:
SELECT cust. name, rcvbles. balance ,...... Other columns
FROM cust, rcvbles
WHERE cust. customer_id = rcvlbes. customer_id
AND rcvblls. balance> 0
AND cust. postcode> 98000"
Order by cust. name
If this query is executed multiple times but more than once, you can find all the unpaid customers and put them in one
View, and sort by customer name:
Create view dbo. V_CUST_RCVLBES
AS
SELECT cust. name, rcvbles. balance ,...... Other columns
FROM cust, rcvbles
WHERE cust. customer_id = rcvlbes. customer_id
AND rcvblls. balance> 0
Order by cust. name

Then, query in the view in the following way:
SELECT * FROM V_CUST_RCVLBES
WHERE postcode> 98000"
The number of rows in the view is smaller than that in the master table, and the physical order is the required order, reducing the disk size.
I/O, so the query workload can be greatly reduced.

12. If you can use BETWEEN, do not use IN.
SELECT * FROM T1 where id in (10, 11, 12, 13, 14)
Changed:
SELECT * FROM T1 where id between 10 AND 14
Because IN will make the system unable to use the index, but can only directly search the data IN the table.

13. DISTINCT does not require GROUP
SELECT OrderID FROM Details WHERE UnitPrice> 10 group by OrderID
You can change it:
Select distinct OrderID FROM Details WHERE UnitPrice> 10
   

14. Partial use of indexes
1. SELECT employeeID, firstname, lastname
FROM names
WHERE dept = 'prod' or city = 'Orlando 'or division = 'food'

2. SELECT employeeID, firstname, lastname FROM names WHERE dept =
'Prod'
UNION ALL
SELECT employeeID, firstname, lastname FROM names WHERE city = 'Orlando'
UNION ALL
SELECT employeeID, firstname, lastname FROM names WHERE division =
'Food'
If the dept column has an index, query 2 can partially use the index, and query 1 cannot.

15. Do not use UNION if union all is used.
Union all does not execute the select distinct function, which reduces unnecessary resources.

16. Do not write any queries that do not do anything.
For example, SELECT COL1 FROM T1 WHERE 1 = 0
SELECT COL1 FROM T1 WHERE COL1 = 1 AND COL1 = 2
This type of dead code does not return any result set, but it consumes system resources.

17. Try not to use the select into statement.
The select into statement will lock the table and prevent other users from accessing the table.

18. When necessary, force the query optimizer to use an index
SELECT * FROM T1 WHERE nextprocess = 1 AND processid IN (8, 32, 45)
Changed:
SELECT * FROM T1 (INDEX = IX_ProcessID) WHERE nextprocess = 1 AND
Processid IN (8, 32, 45)
The query optimizer forcibly uses the index IX_ProcessID to execute the query.
   
19. Although the UPDATE and DELETE statements are basically fixed
Discussion:
A) try not to modify the primary key field.
B) when modifying VARCHAR fields, try to replace them with values of the same length.
C) minimize the UPDATE operations on tables containing UPDATE triggers.
D) avoid columns to be copied to other databases by UPDATE.
E) avoid updating columns with many indexes.
F) avoid updating columns in the WHERE clause condition.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.