在查询中有时使用到伪列rownum对使用伪列rownum的查询,优化器要么使用count操作,要么使用count stopkey操作来对rownum计数器进行增量(注意:这里的count操作和count stopkey操作与count函数没有任何关系),如果对rownum伪列应用一个限定条件,如:where rownum<10;则使用 count stopkey操作,如果不为Rownum伪列指定限定条件,则是使用count操作。
select id,rownum from employee;(在id列上有一个主键索引)为了完成这个查询,优化器执行一个全索引扫描(主键索引),后跟一个count操作生成每个行的rownum值,
count操作不需要等待得到整个记录集,随着从employee表中返回记录,rownum计数器进行增量,从而确定每个记录的rownum.
例2:在rownum伪列上使用一个限定
select id,rownum from employee where rownum<10;
为了实施限定条件,优化器用count stopkey操作代替count操作,它将rownum伪列的增量值与限定条件中指定的值进行比较,如果rownum伪列的值大于限定条件中指定的值,则查询不再返回更多的行!
注意:在where 子句中不能使用 rownum>10这样的操作,只能使用rownum<10这样的操作!
SQL> select rownum rn ,a.* from cnmir.ew_auctions a where rownum<50000;
Execution Plan
----------------------------------------------------------
Plan hash value: 721966694
----------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
----------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 49999 | 4833K| 163 (2)| 00:00:02 |
|* 1 | COUNT STOPKEY | | | | | |
| 2 | TABLE ACCESS FULL| EW_AUCTIONS | 49999 | 4833K| 163 (2)| 00:00:02 |
----------------------------------------------------------------------------------
SQL> select * from cnmir.ew_auctions where issue_id<80;
Execution Plan
----------------------------------------------------------
Plan hash value: 518049957
---------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
---------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 1 | 99 | 1379 (2)| 00:00:17 |
|* 1 | TABLE ACCESS FULL| EW_AUCTIONS | 1 | 99 | 1379 (2)| 00:00:17 |
---------------------------------------------------------------------------------
可见COUNT STOPKEY 机制是只针对rownum而设定的!