简体   繁体   中英

Oracle : ROW_NUMBER 20 times faster than ROWNUM

Tables details :

  • table1 has 20 millions entries
  • table2 has 120 entries.

The target of these requests are to return if yes or no there are exising entries. The number of entries doesn't matter.

Is there someone to explain why

SELECT COUNT(rn) count
FROM
(
 SELECT ROW_NUMBER() OVER (order by t2.id_field) AS rn
 FROM table1 t1
 INNER JOIN table2 t2 ON t2.id_table2 = t1.id_table2
 WHERE t2.id_field = 2
)
WHERE rn < 2;

is 20 times faster than :

SELECT COUNT(rn) count
FROM
(
 SELECT 1 rn
 FROM table1 t1
 INNER JOIN table2 t2 ON t2.id_table2 = t1.id_table2
 WHERE t2.id_field = 2
)
WHERE ROWNUM < 2;

Like said before, ROW_NUMBER() and ROWNUM are not equivalent at all.

The first one is an analytic function which uses a window. Order is specified by order by command.

http://docs.oracle.com/cd/E11882_01/server.112/e26088/functions004.htm#SQLRF51198

select
  ename,
  ROW_NUMBER() OVER (order by ename ) AS rn 
from emp
where deptno =20;

ENAME              RN
---------- ----------
ADAMS               1
FORD                2
JONES               3
SCOTT               4
SMITH               5


Execution Plan
----------------------------------------------------------
Plan hash value: 3145491563

---------------------------------------------------------------------------
| Id  | Operation          | Name | Rows  | Bytes | Cost (%CPU)| Time     |
---------------------------------------------------------------------------
|   0 | SELECT STATEMENT   |      |     5 |    45 |     4  (25)| 00:00:01 |
|   1 |  WINDOW SORT       |      |     5 |    45 |     4  (25)| 00:00:01 |
|*  2 |   TABLE ACCESS FULL| EMP  |     5 |    45 |     3   (0)| 00:00:01 |
---------------------------------------------------------------------------

With rownum:

select ename, 
  ROWNUM
from emp
where deptno =20;

ENAME          ROWNUM
---------- ----------
SMITH               1
JONES               2
SCOTT               3
ADAMS               4
FORD                5


Execution Plan
----------------------------------------------------------
Plan hash value: 1498225739

---------------------------------------------------------------------------
| Id  | Operation          | Name | Rows  | Bytes | Cost (%CPU)| Time     |
---------------------------------------------------------------------------
|   0 | SELECT STATEMENT   |      |     5 |    45 |     3   (0)| 00:00:01 |
|   1 |  COUNT             |      |       |       |            |          |
|*  2 |   TABLE ACCESS FULL| EMP  |     5 |    45 |     3   (0)| 00:00:01 |

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM