Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

189
Views
How to get the count and row list in a single query for pagination?

How to get the count and row list in a single query for pagination in PostgreSQL?

SELECT COUNT(*) FROM employee;
SELECT * FROM employee WHERE employer_id = ? OFFSET 0 LIMIT 25;

Instead of making 2 requests to get the count and rows, Is there a way to do it in a single query?

I have tried the following,

SELECT 
    e.*, 
    (SELECT COUNT(*) FROM employee AS e WHERE e.employer_id = ?) 
FROM employee AS e 
WHERE e.employer_id = ? 
OFFSET 0 LIMIT 25;

but it's inefficient, it requires the same input twice and the count will be calculated in each row.

I there any better way or built-in function to do it?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can use window function:

select *, count(*) over()
from employee e
where e.employer_id = ? 
offset 0 
limit 25

Or if you want to stick to your version, you can leverage cte:

with e_cnt as (
    select count(*) cnt
    from employee
    where e.employer_id = ? 
)
select *, (select cnt from e_cnt)
from employee e
where e.employer_id = ? 
offset 0 
limit 25

Then you know it's evaluated once.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!