Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

190
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda