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

后端 未结 3 712
一整个雨季
一整个雨季 2020-12-06 06:22

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 che

相关标签:
3条回答
  • 2020-12-06 06:47

    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.

    0 讨论(0)
  • 2020-12-06 06:51

    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

    0 讨论(0)
  • 2020-12-06 06:52

    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

    0 讨论(0)
提交回复
热议问题