欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SQL性能调优:1.2 特别语法调优 博客分类: Database SQLOracle 

程序员文章站 2024-02-22 16:49:58
...
from http://www.beyondrails.com/blogs/43

1,一般数据库按从左到右方式解析表达式(Oracle是从右到左),对AND连接的表达式优化顺序,将更小可能发生的表达式放在前面
优化前:
... WHERE column1 = 'A' AND column2 = 'B'

优化后:
... WHERE column2 = 'B' AND column1 = 'A'
(assuming column2 = 'B' is less likely)


2,对OR连接的表达式优化顺序,将更大可能发生的表达式放在前面
优化前:
... WHERE column2 = 'B' OR column1 = 'A'

优化后:
... WHERE column1 = 'A' OR column2 = 'B'
assuming column1 = 'A' is most likely


3,对一系列OR连接的表达式,将相同的column放在一起
优化前:
... WHERE column1 = 1
       OR column2 = 3
       OR column1 = 2

优化后:
... WHERE column1 = 1
       OR column1 = 2
       OR column2 = 3


4,反向使用Distributive Law
优化前:
SELECT * FROM Table1
  WHERE (column1 = 1 AND column2 = 'A')
     OR (column1 = 1 AND column2 = 'B')

优化后:
SELECT * FROM Table1
  WHERE column1 = 1
    AND (column2 = 'A' OR column2 = 'B')


5,将NOT表达式用更易理解的方式替换
优化前:
... WHERE NOT (column1 > 5)

优化后:
... WHERE column1 <= 5


6,将不等号用大于和小于替换
优化前:
... WHERE NOT (bloodtype = 'O')

优化后:
... WHERE bloodtype < 'O'
       OR bloodtype > 'O'


7,将一系列OR连接的表达式用IN替换
优化前:
... WHERE column1 = 5
       OR column1 = 6

优化后:
... WHERE column1 IN (5, 6)


8,当IN后面是一个很密集的整数集时,查找"what is out"比查找"what is in"更好
优化前:
... WHERE column1 IN (1, 3, 4, 5)

优化后:
... WHERE column1 BETWEEN 1 AND 5
      AND column1 <> 2


9,不要将LIKE条件替换为>=,<等等,除非LIKE模式是一个参数如LIKE ?
优化前:
... WHERE column1 LIKE ?

优化后:
... WHERE column1 > SUBSTRING(? FROM 1 FOR 1)
      AND column1 LIKE ?


10,如果LIKE ?参数不带wildcard,并且前后空格等并不关注的话,则用等号来替换LIKE
优化前:
... WHERE column1 LIKE 'ABC'

优化后:
... WHERE column1 = 'ABC'


11,LIKE比多个SUBSTRING效率要高,所以不要替换

12,将UNION转换为OR
优化前:
SELECT * FROM Table1
  WHERE column1 = 5
UNION
SELECT * FROM Table1
  WHERE column2 = 5

优化后:
SELECT DISTINCT * FROM Table1
  WHERE column1 = 5
     OR column2 = 5


13,用CASE表达式来替换多个效率较低的查询条件的引用
优化前:
... WHERE slow_function(column1) = 3
       OR slow_function(column1) = 5

优化后:
... WHERE 1 =
       CASE slow_function(column1)
          WHEN 3 THEN 1
          WHEN 5 THEN 1
       END


14,在SELECT语句的SELECT关键字和FROM关键字之间的东西称为select list。将CASE表达式作为select list的最后的过滤条件。
相关标签: SQL Oracle