1. To optimize the query, avoid full table scan as far as possible, and first consider creating indexes on the columns involved in WHERE and ORDER by.
2. Avoid null values in the WHERE clause. Otherwise, the engine will abandon the use of index and perform full table scan. Select id from t where num is null select id from t where num is null select id from t where num=0
3. Avoid using it in where clauses! = or <> otherwise the engine will abandon the index and perform a full table scan.
Select id from t where num=10 or num=20 select id from t where num=10 or num=20 select id from t where num=10 union all select id from t where num=20
Select id from t where num in(1,2,3) select id from t where num in(1,2,3) select id from t where num between 1 and 3
Select id from t where name like ‘% li %’ select id from t where name like ‘% li %’
7. If you use parameters in the WHERE clause, it will also cause a full table scan. Because SQL resolves local variables only at run time, the optimizer cannot defer the choice of an access plan until run time; It must be selected at compile time. However, if an access plan is established at compile time, the value of the variable is unknown and therefore cannot be used as an input for index selection. Select id from t where num=@num; select id from t with(index) where num=@num
8. Expression operations on fields in the WHERE clause should be avoided as much as possible. This will cause the engine to abandon the use of indexes and perform a full table scan. Select id from t where num/2=100 select id from t where num=100*2
9. Avoid functional manipulation of fields in the WHERE clause, which will cause the engine to abandon indexes and perform a full table scan. Select id from t where substring(name,1,3)= ‘ABC’ select id from t where substring(name,1,3)= ‘ABC’
Select id from t where name like ‘ABC %’
10. Do not perform functions, arithmetic operations, or other expression operations to the left of the “=” in the WHERE clause, or the system may not use the index properly.
11. When using an index field as a condition, if the index is a compound index, the first field in the index must be used as a condition to ensure that the system can use the index. Otherwise, the index will not be used, and the field order should be as consistent as possible with the index order.
Select col1,col2 into #t from t where 1=0
Create table #t(…); create table #t(…);
13. In many cases it is a good choice to use exists instead of in:
Select num from a where exists(select 1 from b where num=a.num)