Tuesday, July 24, 2007

Query to Retrieve 'n' th row from a table

SELECT field_name1,field_name2

FROM table_name

WHERE ROWID = (SELECT ROWID

FROM table_name

WHERE ROWNUM <= :nthrow

MINUS

SELECT ROWID

FROM table_name

WHERE ROWNUM < :nthrow)

The above shown query is one of the way to retrieve the 'n' th row from a table. The same query can be modified in order to provide the rows provided with upper limit and lower limit. say, rows from 5-10.

2 comments:

N Navaneetha Krishnan said...

Few Clarifications regarding the post:

I have heard of the "nth max" or "nth min",
but it looks pretty strange to me as it is about "nth row"!.

1) The retrieval mechanism is dependent on the database implementation. (i.e)
Suppose a table has set of rows say 1 t0 10 in the order,
it need not be the case that the rows are retrieved in the same order.
Simply put, the retreival mechanism will be different from the order it is stored
in the table in the physical layer.

2) Implication from 1). Rownums are "pseudocolumns" that are assigned dynamically based on
the values retrieved!.
Performing operations based on pseudocolumns is not advisable!.

Anonymous said...

Well said.