Oracle where字句优先级
今天在复习Oracle SQL,发现了一个以前一直都没有在意的问题。SQL查询时WHERE后面带有多个子句时,各子句之间有一定的优化关系。大约半年前就碰到过这个问题,当时TSE发给我一个SQL,告诉我说系统存在严重的数据问题,因为这个SQL查出了很多有问题的数据。当时吓得我一身冷汗,然后自己马上连到线上数据库,按照他说的业务需求自己写了个SQL,并执行了一下。我的SQL执行得出的结果并没有他说的数据不对的问题。于是比较了两个SQL,发现在写OR子句的位置有区别。当时只是得出了WHERE子句有一定的关系,但是具体的关系并没有去深入研究。今天在看一个Presentation时终于注意到了一个确切的说法。 在SQL的WHERE后面的多个子句有如下的优先关系:
优先级
1 算术运算符
2 连接符
3 比较符
4 IS [NOT] NULL, LIKE, [NOT] IN
5 [NOT] BETWEEN
6 NOT
7 AND
8 OR
下面用一个例子来证明一下这之间的关系
SQL>SELECT last_name, job_id, salary
2 FROM employees
3 WHERE job_id = 'SA_REP'
4 OR job_id = 'AD_PRES'
5 AND salary > 15000;
执行结果如下:SQL> /
LAST_NAME JOB_ID SALARY
------------------------- ---------- ----------
King AD_PRES 24000
Tucker SA_REP 10000
Bernstein SA_REP 9500
Hall SA_REP 9000
Olsen SA_REP 8000
Cambrault SA_REP 7500
Tuvault SA_REP 7000
King SA_REP 10000
Sully SA_REP 9500
McEwen SA_REP 9000
Smith SA_REP 8000
Doran SA_REP 7500
Sewall SA_REP 7000
Vishney SA_REP 10500
Greene SA_REP 9500
Marvins SA_REP 7200
Lee SA_REP 6800
Ande SA_REP 6400
Banda SA_REP 6200
Ozer SA_REP 11500
Bloom SA_REP 10000
Fox SA_REP 9600
Smith SA_REP 7400
Bates SA_REP 7300
Kumar SA_REP 6100
Abel SA_REP 11000
Hutton SA_REP 8800
Taylor SA_REP 8600
Livingston SA_REP 8400
Grant SA_REP 7000
Johnson SA_REP 6200
31 rows selected
现在修改一下OR的位置再执行一次:
SQL> select last_name,job_id,salary from employees where job_id = 'SA_REP'
2 and salary > 15000 or job_id = 'AD_PRES';
LAST_NAME JOB_ID SALARY
------------------------- ---------- ----------
King AD_PRES 24000
发现两次查询的数据差别非常大。 下面来分析一下执行的过程,我在网上并没有找到确切的描述,下面这些都是我通过对数据观察推断出来的结论。
在第一个SQL中真正执行的应该是如下语句:
select last_name,job_id,salary from employees where job_id = 'SA_REP' or (job_id = 'AD_PRES' and salary > 15000)
因为AND条件比OR高,因此先进行运算
在第二个SQL中是按照where各子句的顺序过滤数据,在执行过程中job_id = 'SA_REP'
and salary > 15000 没有取得符合条件的数据,只有job_id = 'AD_PRES'子句找到了符合条件的数据。 下面执行一下语句验证一下:
SQL> select last_name,job_id,salary from employees where job_id='AD_PRES';
LAST_NAME JOB_ID SALARY
------------------------- ---------- ----------
King AD_PRES 24000
其他几个运算符的优先级也可按照上面的方法来进行分析。
Monday, February 23, 2009
Saturday, February 21, 2009
About this blog
This is another blog.I will post all my thought about computer and software.
I hope i can consistently write...
I hope i can consistently write...
Subscribe to:
Posts (Atom)