Skip to content
Advertisement

Return from first row if last row reached

Table has an id column with rows 1 to 10. I want:

SELECT id FROM `table` WHERE id > 8 ORDER BY id ASC LIMIT 6

to return:

9 10 1 2 3 4

What’s the appropriate query for this?

Advertisement

Answer

SELECT id
FROM `table`
ORDER BY id <= 8, id
LIMIT 6

id <= 8 will be false (0) for 9 and higher, true (1) for values lower than 9, so the higher values will be first. Then within each of those groups it orders by id.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement