Here is another way to do it using UNION
s. I think this is a little easier to understand and more flexible than the accepted answer. Note that the example assumes the id
field is unique, which appears to be the case based on your question.
The SQL query below assumes your table is called demo
and has a single unique id
field, and the table has been populated with the values you listed in your question.
( SELECT id FROM demo WHERE STRCMP ( 'd01', id ) > 0 ORDER BY id DESC LIMIT 1 )
UNION ( SELECT id FROM demo WHERE id = 'd01' ORDER BY id ) UNION
( SELECT id FROM demo WHERE STRCMP ( 'd01', id ) < 0 ORDER BY id ASC LIMIT 1 )
ORDER BY id
It produces the following result: b03, d01, d02
.
This solution is flexible because you can change each of the LIMIT 1
statements to LIMIT N
where N
is any number. That way you can get the previous 3 rows and the following 6 rows, for example.