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

SQL性能调优:1.1 一般性语法调优 博客分类: Database SQLOracle 

程序员文章站 2024-02-22 16:45:40
...
from http://www.beyondrails.com/blogs/42

遵守以下准则:
1,查询条件的左边应该是简单的column名,右边则应该是很容易查询的值
所有的DBMS都会把5 = column1转换为column1 = 5

2,查询条件的每个组件都有一个point count,查询速度越快,花的时间越少,points越高
操作符、操作数                           points
=                                          10
>                                           5
>=                                          5
<                                           5
<=                                          5
LIKE                                        3
<>                                          0
Literal alone                              10
Column alone                                5
Parameter alone                             5
Multioperand expression                     3
Exact numeric data type                     2
Other numeric data type                     1
Temporal data type                          1
Character data type                         0
NULL                                        0

例子
... WHERE smallint_column = 12345

points为27:
1,Column alone(smallint_column) = 5
2,Exact numeric data type(smallint_column) = 2
3,等号 = 10
4,Literal alone(12345) = 10

3,对于多个表达式条件通过优化顺序来提高速度
优化前:
SELECT * FROM Table1
  WHERE column4 < 117
    AND column4 > column5
    AND column3 = 'Smith'
    AND column1 = 5
    AND column2 = 77.3

优化后:
SELECT * FROM Table1
  WHERE column1 = 5
    AND column2 = 77.3
    AND column3 = 'Smith'
    AND column4 < 117
    AND column4 > column5


4,利用Law of Transitivity和Constant propagation的概念,使用字面量来替换column名和column表达式而不改变表达式的含义来提高速度
优化前:
SELECT * FROM Table1
  WHERE column1 = 5 AND
    NOT (column3 = 7 OR column1 = column2)

优化后:
SELECT * FROM Table1
  WHERE column1 = 5
    AND column3 <> 7
    AND column2 <> 5


5,删除那些永远不会执行的代码
SELECT * FROM Table1
  WHERE 0 = 1
    AND column1 = 'I hope we never execute this'


6,有些DBMS不会对大部分obvious-looking表达式做“折叠”,记住一点“更改代码之前先理解它的含义”
... WHERE column1 + 0

... WHERE 5 + 0.0

... WHERE column1 IN (1, 3, 3)

... CAST(1 AS INTEGER)

... WHERE 'a' || 'b'


7,如果代码包括一些显然的算术表达式,则用计算后的值来替换。
优化前:
... WHERE a - 3 = 5

优化后:
... WHERE a = 8


8,尽量避免在column里引入function
优化前:
SELECT * FROM Table1
  WHERE date_column = CURRENT_DATE
    AND amount * 5 > 100.00

优化后:
SELECT * FROM Table1
  WHERE date_column = DATE '2002-01-01'
    AND amount * 5 > 100.00


9,不要使用UPPER来做大小写不敏感的匹配,使用LOWER
优化前:
... WHERE UPPER(column1) = 'résumé'

优化后:
... WHERE LOWER(column1) = 'résumé'
相关标签: SQL Oracle