Tutorials, PHP & MySQL

Select previous and next rows in MySQL

Selecting previous and next rows based on the current row is a common task in most web applications, Take this blog when viewing a post, their are the previous and next posts available at the bottom of each post.

MySQL makes this a simple process the following will get the previous row that has an id less then 2:

Using a sub query in the where clause you can use min and max to return the previous or next row:

//Previous row
SELECT id FROM table WHERE id = (select min(id) from table where id > '2'
​
//next row
SELECT id FROM table WHERE id = (select max(id) from table where id < '2'

 

David Carr

David Carr

For the past 12 years, I’ve been developing applications for the web using mostly PHP. I do this for a living and love what I do as every day there is something new and exciting to learn.

In my spare time, the web development community is a big part of my life. Whether managing online programming groups and blogs or attending a conference, I find keeping involved helps me stay up to date. This is also my chance to give back to the community that helped me get started, a place I am proud to be apart of.

Besides programming I love spending time with friends and family and can often be found together going out catching the latest movie, staying in playing games on the sofa or planning a trip to someplace I’ve never been before.