MrUll's

Mai 19, 2004

Oracle SQL for scrolling forward (get next ID), single SQL Statement

This SQL uses a Oracle-proprietary syntax. See Oracle Data Warehousing Guide, Chapter 19, Windowing Aggregate Functions. Oracle has to be installed with some Options to enable such kinds of queries. To check this, look at the login message (sqlplus):
...
Oracle9i Enterprise Edition Release 9.2.0.4.0 - Production
With the Partitioning, OLAP and Oracle Data Mining options
...
The OLAP option has to be present. Another way to check this is via v$option. There, search for:
OLAP Window Functions TRUE

with this, assume you have a SQL (joins,restrictions,order by) which delivers ids (PK). Given an current ID the question is how to get the next or previous ID (having regard to the restrictions and sort). We use Windowing Functions an inline Views to do this:

Select col1, col2, ...
FROM X
WHERE ID = (
Select id_next
from (
Select Id, last_value(id) over (order by RowNr range between 1 preceding and 1 following) as ID_Next
From (
Select Rownum as RowNr, ID
from (
SELECT Id
FROM X,Y,Z
WHERE ... AND ... AND ...
Order By ID desc
)
)
) where ID=123456
)


here, sortorder is by column value ID. look at the most inner statement. the outer statement just selects cols for the ID whos next (scroll forward) to ID 12346.