PostgreSQL Performance – Optimize Query to Avoid Multiple DB Calls

postgresqlpostgresql-performance

I am running following PostgreSQL query to support my service call for same filter criteria, any thoughts on how we can avoid these two DB calls for the same query and return JSON data in a single query

WITH t as (
SELECT row_to_json(z)::jsonb as record FROM
(
    SELECT  t1.A, t2.B, t1.C 
 FROM Table1 t1
 JOIN Table2 t2 ON t1.id = t2.id) z)

 SELECT record FROM t 
 {=filterParam} ORDER BY {=orderParam} LIMIT(250) OFFSET({=offsetParam});

WITH t as (
SELECT row_to_json(z)::jsonb as record FROM
(SELECT  t1.A, t2.B, t1.C 
 FROM Table1 t1
 JOIN Table2 t2 ON t1.id = t2.id) z)

 SELECT COUNT(record) AS total_record_count From t 
{=filterParam};

I am very beginner to PostgreSQL so all answers are appreciated

Best Answer

You can try to use such query:

WITH t as (
SELECT row_to_json(z)::jsonb as record FROM
(
    SELECT  t1.A, t2.B, t1.C 
          ,COUNT(1) OVER () AS total_record_count 
 FROM Table1 t1
 JOIN Table2 t2 ON t1.id = t2.id) z)

 SELECT record FROM t 
 {=filterParam} ORDER BY {=orderParam} LIMIT(250) OFFSET({=offsetParam});

but your original query doesn't look like the best approach for pagination implementation. Among other factors depending on amount of data you have it may be more efficient to use separate queries. Because server would need to read all rows to calculate total_record_count for any offset and limit.