Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get total count of rows in pagination query

I have the following query for record pagination

SELECT *
  FROM (SELECT e.*, 
               ROWNUM row_num
          FROM (SELECT emp_no,
                       emp_name,
                       dob 
                  from emp) outr
          WHERE ROWNUM < ( (pagenum * row_size) + 1))
 WHERE  row_num >= ( ( (pagenum  - 1) * row_size) + 1)

I would like to get the count of rows as well in same query and for this I have tried using

COUNT(*) OVER ()

however I am not getting accurate results when I am paginating to next set of page and rows.

How can I use COUNT(*) OVER () efficiently?

like image 440
Jacob Avatar asked Oct 15 '13 10:10

Jacob


1 Answers

A typical pagination query with the total number of rows would be:

SELECT *
  FROM (SELECT outr.*,
               ROWNUM row_num
          FROM (SELECT emp_no,
                       emp_name,
                       dob,
                       count(*) over () total_nb
                  FROM emp
                 ORDER BY ...) outr
         WHERE ROWNUM < ((pagenum * row_size) + 1))
 WHERE row_num >= (((pagenum - 1) * row_size) + 1)

Don't forget the ORDER BY.

like image 130
Vincent Malgrat Avatar answered Sep 21 '22 23:09

Vincent Malgrat