注:为读《基于ORACLE SQL优化笔记》
对比RBO 与CBO 在数据选择性不佳的情况下,对执行路径的选择。
select * from emp where mgr = 7902;
1. 骗下优化器,修改表和索引统计信息
2. CBO 对 上面语句选择FULLTABLE SCAN;
3. RBO还是走索引。
数据准备:
CREATE TABLE EMP(EMPNO NUMBER(4) NOT NULL,ENAMEVARCHAR2(10),JOB VARCHAR2(9),MGR NUMBER(4),HIREDATE DATE,SAL NUMBER(7, 2),COMMNUMBER(7, 2),DEPTNO NUMBER(2));
INSERT INTO EMP VALUES(7369, 'SMITH', 'CLERK',7902,TO_DATE('17-DEC-1980', 'DD-MON-YYYY'), 800, NULL, 20);
INSERT INTO EMP VALUES(7499, 'ALLEN', 'SALESMAN',7698,TO_DATE('20-FEB-1981', 'DD-MON-YYYY'), 1600, 300, 30);
INSERT INTO EMP VALUES(7521, 'WARD', 'SALESMAN',7698,TO_DATE('22-FEB-1981', 'DD-MON-YYYY'), 1250, 500, 30);
INSERT INTO EMP VALUES(7566, 'JONES', 'MANAGER',7839,TO_DATE('2-APR-1981', 'DD-MON-YYYY'), 2975, NULL, 20);
INSERT INTO EMP VALUES(7654, 'MARTIN', 'SALESMAN',7698,TO_DATE('28-SEP-1981', 'DD-MON-YYYY'), 1250, 1400, 30);
INSERT INTO EMP VALUES(7698, 'BLAKE', 'MANAGER',7839,TO_DATE('1-MAY-1981', 'DD-MON-YYYY'), 2850, NULL, 30);
INSERT INTO EMP VALUES(7782, 'CLARK', 'MANAGER',7839,TO_DATE('9-JUN-1981', 'DD-MON-YYYY'), 2450, NULL, 10);
INSERT INTO EMP VALUES(7788, 'SCOTT', 'ANALYST',7566,TO_DATE('09-DEC-1982', 'DD-MON-YYYY'), 3000, NULL, 20);
INSERT INTO EMP VALUES(7839, 'KING', 'PRESIDENT',NULL,TO_DATE('17-NOV-1981', 'DD-MON-YYYY'), 5000, NULL, 10);
COMMIT;
ALTER TABLE EMP MODIFY (MGR NOT NULL);
CREATE INDEX IDX_EMP_MGR ON EMP(MGR);
set autotrace on
--修改表统计信息
EXEC dbms_stats.set_table_stats(ownname=>'tester',tabname=>'EMP',numrows =>1000000,no_invalidate =>false);
--修改索引统计信息
EXEC dbms_stats.set_index_stats(ownname=>'tester',indname=>'IDX_EMP_MGR',numlblks =>100000,no_invalidate=>false);
--默认CBO:
select * from emp where mgr = 7902;
--当前 SESSION 改为RBO:
Alter session set optimizer_mode =rule;
select * from emp where mgr = 7902;