1、能用DISTINCT的就不用GROUP BY
SELECT OrderID FROM Details WHERE UnitPrice > 10 GROUP BY OrderID
可改为: SELECT DISTINCT OrderID FROM Details WHERE UnitPrice > 10
2.能用UNION ALL就不要用UNION
UNION ALL不执行SELECT DISTINCT函数,这样就会减少很多不必要的资源
3.尽量不要用SELECT INTO语句。
SELECT INOT 语句会导致表锁定,阻止其他用户访问该表。
4.能够用BETWEEN的就不要用IN
5.exists代替in
select num from a where num in(select num from b)
可改为: select num from a where exists(select 1 from b where num=a.num)
6.避免在 where 子句中对字段进行表达式操作(计算、Format等等),这将导致引擎放弃使用索引而进行全表扫描。
如: SELECT * FROM T1 WHERE F1/2=100
应改为: SELECT * FROM T1 WHERE F1=100*2
SELECT * FROM RECORD WHERE SUBSTRING(CARD_NO,1,4)=?5378?
应改为: SELECT * FROM RECORD WHERE CARD_NO LIKE ?5378%?
SELECT member_number, first_name, last_name FROM members WHERE DATEDIFF(yy,datofbirth,GETDATE()) > 21
应改为: SELECT member_number, first_name, last_name FROM members WHERE dateofbirth < DATEADD(yy,-21,GETDATE())
即:任何对列的操作都将导致表扫描,它包括数据库函数、计算表达式等等,查询时要尽可能将操作移至等号右边。
7.表中是否存在某条纪录不要用count(*)那样效率很低,而且浪费服务器资源。可以用EXISTS代替。
如: IF (SELECT COUNT(*) FROM table_name WHERE column_name = ?xxx?)
可以写成: IF EXISTS (SELECT * FROM table_name WHERE column_name = ?xxx?)