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

433
Views
Postgres - how to get proper count with join

Sorry as a newcomer to sql (postgres in this case) I can't tease out the right answer from similar questions. So here's an example

I have two tables:

records:

id    |  status 
----------------
1     | open
2     | open
3     | close
4     | open

events:

id    | record_id  | role   | something_else
---------------------------------------------
1     |  2         | admin  | stringA
2     |  1         | user   | stringB
3     |  4         | admin  | stringC
4     |  2         | admin  | stringD
5     |  2         | admin  | stringE
6     |  2         | user   | stringF  
7     |  3         | user   | stringG

I basically would like to have a count(status) that reflects how many records have at least one events.role = 'admin' in the events table

in the above example it would be:

status | count 
---------------
open   |   2
close  |   0

Any help much appreciated!

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

No need for nested queries. You can just use conditional aggregation:

select r.status, count(distinct r.id) filter(where e.role = 'admin') cnt
from records r
inner join events e on e.record_id = r.id
group by r.status

Demo on DB Fiddle:

status | cnt
:----- | --:
close  |   0
open   |   2
over 4 years ago · Santiago Trujillo Report

0

I basically would like to have a count(status) that reflects how many records have at least one events.role = 'admin' in the events table.

I would suggest:

select r.status, count(*) filter (where has_admin)
from (select r.*, 
             (exists (select 1 from events e where e.record_id = r.id and e.role = 'admin')) as has_admin
      from records r
     ) r
group by r.status;

For your small data sample, the difference between exists and a join doesn't matter. With more data, though, the exists does not multiply the number of rows, which should make it a bit faster. Also, this guarantees that all statuses are included, even those with no events.

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!