SELECT CASE WHEN sender_id = 1
THEN receiver_id
ELSE sender_id
END AS buddy
FROM message
WHERE 1 IN (sender_id, receiver_id)
GROUP BY buddy
ORDER BY MAX(sent_at)
SELECT user.username
FROM user
JOIN ( SELECT CASE WHEN sender_id = 1
THEN receiver_id
ELSE sender_id
END AS id,
MAX(sent_at) sent_at
FROM message
WHERE 1 IN (sender_id, receiver_id)
GROUP BY 1 ) ids USING (id)
ORDER BY ids.sent_at