I'm building a messaging feature for an app, my database table looks like this:
messages:
id
senderId
receiverId
threadId <-- every message is part of a thread
createdAt
I have a 'Messages' page which has a card for every message thread, but I want it to show the latest message in the card as a preview for each thread. This is the query I've written so far:
SELECT DISTINCT ON ("threadId") * FROM messages ORDER BY "createdAt" DESC;
So I'm doing DISTINCT ON ("threadId")
, but I'm also selecting all the columns because I want all the data, that's why there's a *
after the DISTINCT ON
clause. This query worked fine up until this point, but now it's failing on the ORDER BY
clause. I want to return the message that was created last, but I'm getting an error:
ERROR: SELECT DISTINCT ON expressions must match initial ORDER BY expressions LINE 1: SELECT DISTINCT ON ("threadId") * FROM messages order by "cr...
I understand the error I think (the ORDER BY
column has to match the column that DISTINCT ON
is being applied to) but I don't know how to get the query to be what I want, which is to be ordered by createdAt
before it becomes distinct.