rownum
が前に適用されるORDER BY
ため、クエリはほぼ確実に期待どおりに動作しません。クエリは基本的に任意の3行を要求しており、ORDER BY
何も役に立ちません。
row_number
代わりに分析関数を使用できます。
SELECT *
FROM (SELECT a.*,
row_number() over (order by userid asc) rn
FROM activeSessionsLog a)
WHERE rn BETWEEN 8 AND 10
結果をページングします
SQL> ed
Wrote file afiedt.buf
1 select empno, ename, job
2 from (select e.*,
3 row_number() over (order by empno) rn
4 from emp e)
5* where rn between 1 and 3
SQL> /
EMPNO ENAME JOB
---------- ---------- ---------
7369 SMITH CLERK
7499 ALLEN SALESMAN
7521 WARD SALESMAN
SQL> ed
Wrote file afiedt.buf
1 select empno, ename, job
2 from (select e.*,
3 row_number() over (order by empno) rn
4 from emp e)
5* where rn between 4 and 8
SQL> /
EMPNO ENAME JOB
---------- ---------- ---------
7566 JONES MANAGER
7654 MARTIN SALESMAN
7698 BLAKE MANAGER
7782 CLARK MANAGER
7788 SCOTT ANALYST
SQL> ed
Wrote file afiedt.buf
1 select empno, ename, job
2 from (select e.*,
3 row_number() over (order by empno) rn
4 from emp e)
5* where rn between 9 and 11
SQL> /
EMPNO ENAME JOB
---------- ---------- ---------
7839 KING PRESIDENT
7844 TURNER SALESMAN
7876 ADAMS CLERK
rownum <= 10
ただし、Oracleが内部述語を使用して、最初の10行を識別した後、データの並べ替えを停止できることを知ることができるこのようなことを行う方が効率的かもしれません。
SELECT c.*
FROM (SELECT b.*, rownum rn
FROM (SELECT a.*
FROM activeSessionsLog a
ORDER BY userid asc) b
WHERE rownum <= 10) c
WHERE rn >= 8