Find the previous / following records when you get an alphabetical order in sql?


I have a table people

id    name
54    Tango
76    Alpha
95    Radio

When displaying the records on the web those names are ordered alphabetically

Alpha, Radio, Tango

Lets say we're viewing Radio details and want to navigate to the next (Tango) or prevoius (Alpha) record using some links.

How can I find those id's to create the needed links?

Finding next superior or inferior id won't work.

Is this possible?


You can do this:

   SELECT name, (@rownum := @rownum + 1) rank
   FROM people, (SELECT @rownum := 0) t
   ORDER BY name
) t WHERE rank = @n

You should use the new ranking number column rank to create those links. Then you should control the value of the parameter @n to get the previous or the next.

SQL Fiddle Demo