Skip to content

Instantly share code, notes, and snippets.

@Hiweus
Last active March 30, 2023 02:11
Show Gist options
  • Save Hiweus/7f3d2f8a9b8c6a7c901aae39ef0dd7fe to your computer and use it in GitHub Desktop.
Save Hiweus/7f3d2f8a9b8c6a7c901aae39ef0dd7fe to your computer and use it in GitHub Desktop.
Fetch last elements on table in each group

Fetch the last messages in each group by the attribute name

SELECT m1.*
FROM messages m1 LEFT JOIN messages m2
 ON (m1.name = m2.name AND m1.id < m2.id)
WHERE m2.id IS NULL;
SELECT *
FROM messages where id in (
  select max(id) from messages group by name
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment