Skip to content

Instantly share code, notes, and snippets.

@philleepflorence
Last active February 13, 2016 16:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philleepflorence/f1126dd47b9181db2265 to your computer and use it in GitHub Desktop.
Save philleepflorence/f1126dd47b9181db2265 to your computer and use it in GitHub Desktop.
Get the next record in a SQL table. Returns to the start of the table if current record is the last.
SELECT * FROM [table]
WHERE
(
id = IFNULL( ( SELECT MIN(id) FROM [table] WHERE id > [current id] ), 0 )
OR
id = IFNULL( ( SELECT MIN(id) FROM [table] WHERE id > 0 ), 0 )
)
LIMIT 1;
# [table] and [current id] are required.
# First sub query gets the next record. MIN(id) acts as the id + 1.
# Second sub query gets the first available record (start) in the table.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment