I have the following log table for user messages (simplified form) in Postgres 9.2:
CREATE TABLE log (
log_date DATE,
user_id INTEGER,
payload
Perhaps a different index on the table would help. Try this one: log(user_id, log_date)
. I am not positive that Postgres will make optimal use with distinct on
.
So, I would stick with that index and try this version:
select *
from log l
where not exists (select 1
from log l2
where l2.user_id = l.user_id and
l2.log_date <= :mydate and
l2.log_date > l.log_date
);
This should replace the sorting/grouping with index look ups. It might be faster.