Best practice for pagination in Oracle?

前端 未结 7 1393
别那么骄傲
别那么骄傲 2020-11-28 07:22

Problem: I need write stored procedure(s) that will return result set of a single page of rows and the number of total rows.

Solution A: I create tw

7条回答
  •  再見小時候
    2020-11-28 07:58

    If you're already using analytics (ROW_NUMBER() OVER ...) then adding another analytic function on the same partitioning will add a negligible cost to the query.

    On the other hand, there are many other ways to do pagination, one of them using rownum:

    SELECT * 
      FROM (SELECT A.*, rownum rn
              FROM (SELECT *
                      FROM your_table
                     ORDER BY col) A
             WHERE rownum <= :Y)
     WHERE rn >= :X
    

    This method will be superior if you have an appropriate index on the ordering column. In this case, it might be more efficient to use two queries (one for the total number of rows, one for the result).

    Both methods are appropriate but in general if you want both the number of rows and a pagination set then using analytics is more efficient because you only query the rows once.

提交回复
热议问题