+92 332 4229 857 99ProjectIdeas@Gmail.com

How to get the previous or the next value from a table in MySQL



This data set will be used as sample for the following examples.




How to get the previous value from a table in MySQL

This will select the previous value of the attribute.
SELECT *
FROM table_name
WHERE column_name < @VALUE
ORDER BY column_name DESC
LIMIT 1

Example

SELECT *
FROM categories
WHERE category_id < 5
ORDER BY category_id DESC
LIMIT 1




How to get the next value from a table in MySQL

This will select the next value of the attribute.
SELECT *
FROM table_name
WHERE column_name > @VALUE
ORDER BY column_name ASC
LIMIT 1

Example

SELECT *
FROM categories
WHERE category_id > 5
ORDER BY category_id ASC
LIMIT 1