I am writing a chat app and want to get a list of recent contacts to show in the sidebar.
My table has the standard chat fields (sender, receiver, msg, date)
.
I'm currently getting a list of recent contacts by getting a list of messages with distinct (sender, receiver)
pair:
select * from (
select distinct on (sender, receiver) *
from (
select *
from chats
where sender = login or receiver = login
order by date desc
) as Q1
limit 30
) as Q2
order by date desc
The result returned is wrong as it doesn't contain the newest messages.
I found that I could fix it by flipping the first order by
to order by date asc
. I only need to flip the first asc
and not the second.
Does anyone know why it works?
My only guess is that DISTINCT ON
is filtering from the bottom of the list rather than from the top.