ROWNUM is a pseudo column that is assigned an incremental and unique integer value for each row based on the order the rows were retrieved from a query. Therefore, the first row retrieved has ROWNUM of 1. The second row has ROWNUM of 2. The other rows follow similar rules.
This feature can be used to limit the number of rows retrieved by a query. The following example shows how this feature works:
SELECT empno, ename, job FROM emp WHERE ROWNUM < 5;
empno | ename | job
-------+-------+----------
7369 | SMITH | CLERK
7499 | ALLEN | SALESMAN
7521 | WARD | SALESMAN
7566 | JONES | MANAGER
(4 rows)
The ROWNUM value is assigned to each row before the result set is sorted. The result set is returned in the order specified by the ORDER BY clause, but the ROWNUM values may not be sorted in ascending order. The following example shows how the result set and ROWNUM values are returned:
SELECT ROWNUM, empno, ename, job FROM emp WHERE ROWNUM < 5 ORDER BY ename;
rownum | empno | ename | job
--------+-------+-------+----------
2 | 7499 | ALLEN | SALESMAN
4 | 7566 | JONES | MANAGER
1 | 7369 | SMITH | CLERK
3 | 7521 | WARD | SALESMAN
(4 rows)
The following example shows how a sequence number can be added to each row in the jobhist table. A new column named seqno is added to the table and then the seqno column is set to ROWNUM in the UPDATE statement.
ALTER TABLE jobhist ADD seqno NUMBER(3);
UPDATE jobhist SET seqno = ROWNUM;
The following SELECT statement shows the new values of the seqno column.
SELECT seqno, empno, TO_CHAR(startdate,'DD-MON-YY') AS start, job FROM jobhist;
seqno | empno | start | job
-------+-------+-----------+-----------
1 | 7369 | 17-DEC-80 | CLERK
2 | 7499 | 20-FEB-81 | SALESMAN
3 | 7521 | 22-FEB-81 | SALESMAN
4 | 7566 | 02-APR-81 | MANAGER
5 | 7654 | 28-SEP-81 | SALESMAN
6 | 7698 | 01-MAY-81 | MANAGER
7 | 7782 | 09-JUN-81 | MANAGER
8 | 7788 | 19-APR-87 | CLERK
9 | 7788 | 13-APR-88 | CLERK
10 | 7788 | 05-MAY-90 | ANALYST
11 | 7839 | 17-NOV-81 | PRESIDENT
12 | 7844 | 08-SEP-81 | SALESMAN
13 | 7876 | 23-MAY-87 | CLERK
14 | 7900 | 03-DEC-81 | CLERK
15 | 7900 | 15-JAN-83 | CLERK
16 | 7902 | 03-DEC-81 | ANALYST
17 | 7934 | 23-JAN-82 | CLERK
(17 rows)