Skip to content

Instantly share code, notes, and snippets.

@djvs
Created February 7, 2016 07:50
Show Gist options
  • Save djvs/fe3b8d531fbd45ad5b6c to your computer and use it in GitHub Desktop.
Save djvs/fe3b8d531fbd45ad5b6c to your computer and use it in GitHub Desktop.
SELECT DISTINCT ON (user_id) *
FROM (
SELECT 'out' AS type, id, recipient_id AS user_id, body, created_at
FROM messages
WHERE sender_id = 57
UNION ALL
SELECT 'in' AS type, id, sender_id AS user_id, body, created_at
FROM messages
WHERE recipient_id = 57
) sub
ORDER BY user_id, created_at DESC;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment