I'm developing a real-time chat app using PostgreSQL and I'm having the following issue:
When a user logs in, I need to fetch all the users that are not the logged-in user, in order to display them on the sidebar of the app.
Below each user should be displayed the latest message that was sent either by the logged-in user or by the other user.
I'm trying to execute an efficient query in order to retrieve all the users with their latest message at once but with no success.
Here are my tabels:
I tried at first to do something like that:
SELECT users.id, users.first_name, users.last_name, users.image, messages.sender_id, messages.recipient_id, messages.content
FROM users LEFT JOIN messages on users.id = messages.sender_id OR users.id = messages.recipient_id
WHERE (messages.sender_id = 1 OR messages.recipient_id = 1) AND users.id != 1
GROUP BY users.id
ORDER BY messages.created_at DESC;
And I got this error:
- "1" refers to the logged user id
My temporary solution is to fetch all the users from the db, mapping over them on the server and executing another query which sends back the latest message between the users using - ORDER BY created_at DESC LIMIT 1.
I'm sure there are more efficient ways, and I would appreciate any help!



GROUP BYin posted query? Is this posted query the temporary solution used in app? What is the question here exactly? Is current query running slow? Please describe better but with no success. Errors? Undesired results? Slow process?