How to add offset in a “select” query in Oracle 11g?

不问归期 提交于 2019-12-17 16:27:56

问题


How to add an offset in a "select" query in Oracle 11g. I only know how to add the limit by e.g rownum <= 5 this question is not a duplicate, I already checked the other questions and are not related to mine.

So, how to add the offset in Oracle 11g ?


回答1:


You can do it easily on 12c by specifying OFFSET.

In 12c,

SELECT val
FROM   table
ORDER BY val
OFFSET 4 ROWS FETCH NEXT 4 ROWS ONLY;

To do the same on 11g and prior, you need to use ROWNUM twice, inner query and outer query respectively.

The same query in 11g,

SELECT val
FROM   (SELECT val, rownum AS rnum
        FROM   (SELECT val
                FROM   table
                ORDER BY val)
        WHERE rownum <= 8)
WHERE  rnum > 4;

Here OFFSET is 4.




回答2:


You can use ROW_NUMBER function for that.

Maybe this helps:

SELECT *
  FROM(SELECT t.*,
              ROW_NUMBER() OVER (ORDER BY ...) rn -- whatever ordering you want
         FROM your_table t
      )
 WHERE rn >= ... -- your offset

Hope that helps




回答3:


Use the function LAG or LEAD in oracle

The LAG function is used to access data from a previous row

The LEAD function is used to return data from the next row

Usage:-

LAG  (value_expression [,offset] [,default]) OVER ([query_partition_clause] order_by_clause)
LEAD (value_expression [,offset] [,default]) OVER ([query_partition_clause] order_by_clause)

Please find the this link for examples



来源:https://stackoverflow.com/questions/27099414/how-to-add-offset-in-a-select-query-in-oracle-11g

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!