Created
July 31, 2026 22:51
-
-
Save thiagoa/9bcec7dba3676522c785d580d4f25af1 to your computer and use it in GitHub Desktop.
MAX(id) variation for finding the latest row and why it can break
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -- A common variation uses MAX(id) to find the latest status: | |
| SELECT u.id, s.status | |
| FROM users u | |
| JOIN user_statuses s ON s.user_id = u.id | |
| WHERE s.id = ( | |
| SELECT MAX(id) FROM user_statuses s2 WHERE s2.user_id = u.id | |
| ); | |
| -- This assumes the highest id is always the latest status. | |
| -- That holds under normal operation, but breaks during backfills | |
| -- or data corrections where older statuses may be inserted with | |
| -- higher IDs. ORDER BY created_at DESC, id DESC expresses the | |
| -- business rule directly and doesn't depend on insertion order. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment