Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the next record after a specified one in SQL?

Tags:

I'd like to use a single SQL query (in MySQL) to find the record which comes after one that I specify.

I.e., if the table has:

id, fruit --  ----- 1   apples 2   pears 3   oranges 

I'd like to be able to do a query like:

SELECT * FROM table where previous_record has id=1 order by id; 

(clearly that's not real SQL syntax, I'm just using pseudo-SQL to illustrate what I'm trying to achieve)

which would return:

2, pears 

My current solution is just to fetch all the records, and look through them in PHP, but that's slower than I'd like. Is there a quicker way to do it?

I'd be happy with something that returned two rows -- i.e. the one with the specified value and the following row.

EDIT: Sorry, my question was badly worded. Unfortunately, my definition of "next" is not based on ID, but on alphabetical order of fruit name. Hence, my example above is wrong, and should return oranges, as it comes alphabetically next after apples. Is there a way to do the comparison on strings instead of ids?

like image 477
Ben Avatar asked Dec 31 '08 13:12

Ben


People also ask

How do I find the next record in SQL?

You can use UNION to get the previous and next record in MySQL. Insert some records in the table using insert command. Display all records from the table using select statement.

How do I find the next value of a sequence in SQL Server?

SELECT - For each referenced sequence object, a new value is generated once per row in the result of the statement. INSERT ... VALUES - For each referenced sequence object, a new value is generated once for each inserted row in the statement.

How can I get data between specific dates in SQL?

SELECT * FROM ATM WHERE TRANSACTION_TIME BETWEEN '2005-02-28 21:00:00' AND '2008-12-25 00:00:00';

What is fetch next in SQL?

If FETCH NEXT is the first fetch against a cursor, it returns the first row in the result set. NEXT is the default cursor fetch option. Returns the result row immediately preceding the current row, and decrements the current row to the row returned.


2 Answers

After the question's edit and the simplification below, we can change it to

SELECT id FROM table WHERE fruit > 'apples' ORDER BY fruit LIMIT 1 
like image 74
Vinko Vrsalovic Avatar answered Sep 20 '22 14:09

Vinko Vrsalovic


SELECT * FROM table WHERE id > 1 ORDER BY id LIMIT 1 

Even simpler

UPDATE:

SELECT * FROM table  WHERE fruit > 'apples' ORDER BY fruit LIMIT 1 
like image 32
Ólafur Waage Avatar answered Sep 16 '22 14:09

Ólafur Waage