For each row returned by a query, the
You can use
ROWNUM
pseudocolumn returns a number indicating the order in which Oracle selects the row from a table or set of joined rows. The first row selected has a ROWNUM
of 1, the second has 2, and so on.You can use
ROWNUM
to limit the number of rows returned by a query, as in this example:SELECT * FROM employees WHERE ROWNUM < 10; If anORDER
BY
clause followsROWNUM
in the same query, then the rows will be reordered by theORDER
BY
clause. The results can vary depending on the way the rows are accessed. For example, if theORDER
BY
clause causes Oracle to use an index to access the data, then Oracle may retrieve the rows in a different order than without the index. Therefore, the following statement will not have the same effect as the preceding example:
SELECT * FROM employees WHERE ROWNUM < 11 ORDER BY last_name;If you embed the
ORDER
BY
clause in a subquery and place the ROWNUM
condition in the top-level query, then you can force the ROWNUM
condition to be applied after the ordering of the rows. For example, the following query returns the employees with the 10 smallest employee numbers. This is sometimes referred to as top-N reporting:SELECT * FROM (SELECT * FROM employees ORDER BY employee_id) WHERE ROWNUM < 11;In the preceding example, the
ROWNUM
values are those of the top-level SELECT
statement, so they are generated after the rows have already been ordered by employee_id
in the subquery.Conditions testing for
ROWNUM
values greater than a positive integer are always false. For example, this query returns no rows:SELECT * FROM employees WHERE ROWNUM > 1;The first row fetched is assigned a
ROWNUM
of 1 and makes the condition false. The second row to be fetched is now the first row and is also assigned a ROWNUM
of 1 and makes the condition false. All rows subsequently fail to satisfy the condition, so no rows are returned.You can also use
ROWNUM
to assign unique values to each row of a table, as in this example:UPDATE my_table SET column1 = ROWNUM; Suppose I have a table with 5 rows:
SELECT * FROM EMP; EMPID POSITION_NAME 5 SALES REP 4 SUPERVISOR 3 AREA MANAGER 2 SALES MANAGER 1 REGIONAL DIRECTOR SELECT * FROM EMP WHERE ROWNUM<4 font="">4>
EMPID POSITION_NAME
5 SALES REP 4 SUPERVISOR 3 AREA MANAGER SELECT * FROM EMP WHERE ROWNUM=1;
EMPID POSITION_NAME
5 SALES REP SELECT * FROM EMP WHERE ROWNUM=2;
No Rows Returned
-- Choosing any value other than 1 will be false.
SELECT * FROM EMP WHERE ROWNUM>1;
No Rows Returned
SELECT * FROM EMP WHERE ROWNUM>2;
No Rows Returned -- Choosing any value greater than 1 will be false. Explained above ROWNUM works with =1 or less thanonly. When used in Sub-queries ROWNUM allow us to view data providing range of rows. It's like mentioning a window for viewing the data. SELECT * FROM (SELECT rownum r1, t.* from r_roche_terr_position t) WHERE r1 > 1 and r1<4 font=""> 4>R1 EMPID POSITION_NAME
2 4 SUPERVISOR
3 3 AREA MANAGER
0 comments:
Post a Comment