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

188
Views
Select newest entry for each user without using group by (postgres)

I have a table myTable with four columns:

id        UUID,
user_id   UUID ,
text      VARCHAR ,
date      TIMESTAMP

(id is the primary key and user_id is not unique in this table)

I want to retrieve the user_ids ordered by their newest entry, which i am currently doing with this query:

SELECT user_id FROM myTable GROUP BY user_id ORDER BY MAX(date) DESC

The problem is that GROUP BY takes a long time. Is there a faster way to accomplish this? I tried using a window function with PARTITION BY as described here Retrieving the last record in each group - MySQL, but it didn't really speed things up. I've also made sure that user_id is indexed.

My postgres version is 10.4

Edit: The query above that I'm currently using is functionally correct, the problem is that it's slow.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Your query seems like a relevant approach for your requirement:

select user_id 
from mytable 
group by user_id 
order by max(date) desc

I would recommend an index on (user, date desc) to speed things up. It needs to be a single index on both colums.

You could also give a try to distinct on, which might, or might not, give you better performance:

select user_id
from (
    select distinct on(user_id) user_id, date
    from mytable
    order by user_id, date desc
) t
order by date desc
over 4 years ago · Santiago Trujillo Report

0

Start with an index on user_id, date desc. That might help.

You can also try filtering -- once you have such an index:

select t.user_id
from myTable t
where t.date = (select max(t2.date)
                from myTable t2
                where t2.user_id = t.user_id
               )
order by t.date desc

However, you might find that the order by ends up taking almost as much time as the group by.

This version will definitely use the index for the subquery:

select user_id
from (select distinct on (user_id) user_id, date
      from myTable t
      order by user_id, date desc
     ) t
order by date desc;
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!