0

In Datatables I use two query one to fetch records in that particular date range with server side pagination and another to get the total count of records in that particular date range. I am using Postgresql database.

select * from daily_txns where created_date <='2017-08-01' and created_date>='2017-07-01' and mid='0446721M0008690' order by created_date desc limit 10;

select count(mid) from daily_txns where created_date <='2017-08-01' and created_date>='2017-07-01' and mid='0446721M0008690';

Is this the correct way to do or is there any best approach for the same. If the first query takes 20 sec then the second query takes 40 sec and the total time taken to display the result is more then 60 sec. How to overcome this problem.

Vijayanand Premnath
  • 3,415
  • 4
  • 25
  • 42

3 Answers3

0

If you are using postgres you can use this to reduce everything to one single query

select *, count(*) OVER() AS full_count from daily_txns where created_date <='2017-08-01' and created_date>='2017-07-01' and mid='0446721M0008690' order by created_date desc limit 10;

the "count(*) OVER() AS full_count" will 'ignore' the limits passed giving you the full count of possible elements

Brugolo
  • 4,685
  • 3
  • 22
  • 14
0

Solution depends on your table indexes and this answer only if indexes correct and you solutions like count(*) doesn't help you.

But sometimes you can try to use flag SQL_CALC_FOUND_ROWS for your query, but I recommend to read this question and answer before use it.

Solution:

select SQL_CALC_FOUND_ROWS * from daily_txns where created_date <='2017-08-01' and created_date>='2017-07-01' and mid='0446721M0008690' order by created_date desc limit 10;

And query for get total records for your query

SELECT FOUND_ROWS() as cnt
Dmitriy.Net
  • 1,476
  • 13
  • 24
0

You need to add an index to the columns mid and created_date on the table daily_txns. I'm also guessing that mid will be more restrictive than created_date, so I recommend using it first in the query so that the search reduces faster.

select * from daily_txns where mid='0446721M0008690' created_date <='2017-08-01' and created_date>='2017-07-01' order by created_date desc limit 10;

select count(mid) from daily_txns where mid='0446721M0008690' and created_date <='2017-08-01' and created_date>='2017-07-01';
Altimus Prime
  • 2,207
  • 2
  • 27
  • 46