Select previous and next rows in MySQL

David Carr

Tutorials PHP & 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'

 

Laravel Modules Your Logo Your Logo Your Logo

Become a sponsor

Help support the blog so that I can continue creating new content!

Sponsor

My Latest Book

Modular Laravel Book - Laravel: The Modular way

Learn how to build modular applications with Laravel Find out more

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Fathom Analytics $10 discount on your first invoice using this link

© 2006 - 2024 DC Blog. All code MIT license. All rights reserved.