How ROWNUM works in pagination query?
You have 4 questions, and all revolve around the usage and functionality of ROWNUM. I will answer each question one-by-one.
Why (this was my first attempt until I search on SO) Select * From Person Where rownum > 100 and rownum < 110; returns 0 rows ?
Nice explanation by Thomas Kyte regarding ROWNUM and pagination here.
A ROWNUM value is assigned to a row after it passes the predicate phase of the query but before the query does any sorting or aggregation. Also, a ROWNUM value is incremented only after it is assigned, which is why the following query will never return a row:
select * from t where ROWNUM > 1;
Because ROWNUM > 1 is not true for the first row, ROWNUM does not advance to 2. Hence, no ROWNUM value ever gets to be greater than 1.
Why there is no simple way to do something like Select ... FROM ... WHERE rownum BETWEEN lowerBound AND upperBound ?
Yes, there is. From Oracle 12c onwards, you could use the new Top-n Row limiting feature. See my answer here.
For example, the below query would return the employees between 4th highest till 7th highest salaries in ascending order:
SQL> SELECT empno, sal 2 FROM emp 3 ORDER BY sal 4 OFFSET 4 ROWS FETCH NEXT 4 ROWS ONLY; EMPNO SAL---------- ---------- 7654 1250 7934 1300 7844 1500 7499 1600SQL>
How to get rid of the r column in the resulting values?
Instead of select *
, list the required column names in the outer query. For frequently using the query, creating a view is a simple one time activity.
Alternatively, in SQL*Plus
you could use the NOPRINT command. It will not display the column name you don't want to display. However, it would only work in SQL*Plus.
For example,
COLUMN column_name NOPRINT
For example,
SQL> desc dept Name Null? Type ----------------------------------------- -------- ------------ DEPTNO NUMBER(2) DNAME VARCHAR2(14) LOC VARCHAR2(13)SQL> COLUMN dname NOPRINTSQL> COLUMN LOC NOPRINTSQL> SELECT * FROM dept; DEPTNO---------- 10 20 30 40SQL>
Does it ensure correct pagination?
Yes, if you write the pagination query correctly.
For example,
SELECT valFROM (SELECT val, rownum AS rnum FROM (SELECT val FROM t ORDER BY val) WHERE rownum <= 8)WHERE rnum >= 5; VAL---------- 3 3 4 44 rows selected.SQL>
Or, use the new row limiting feature on 12c as I have shown above.
Few good examples here.
Answer to question 2: In Oracle 12 you can use pagination
select owner, object_name, object_idfrom torder by owner, object_nameOFFSET 5 ROWS FETCH NEXT 5 ROWS ONLY;
I usually write a query like this:
select * from ( select a.*, rownum as rn from table_name a where rownum <= 110)where rn > 100