Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql Query, Select greater than

Tags:

sql

mysql

I've got a table, called faq_questions with the following structure:

id int not_null auto_increment,
question varchar(255),
sort_order int

I'm attempting to build a query that given a sort order, selects the row with the next highest sort order.

Example:

id  question                sort_order
1   'This is question 1'    10
2   'This is question 2'    9
3   'This is another'       8
4   'This is another one'   5
5   'This is yet another'   4

Ok, so imagine I pass in 5 for my known sort order (id 4), I need it to return the row with id 3. Since there's no guarantee that sort_order will be contiguous I can't just select known_sort_order + 1.

Thanks!

like image 785
Electronic Zebra Avatar asked Dec 11 '08 21:12

Electronic Zebra


People also ask

What is == in SQL?

== (Equal) (SSIS Expression)

How do you say not equal to in MySQL?

not equal to (<>, !=) operator. MySQL Not equal is used to return a set of rows (from a table) after making sure that two expressions placed on either side of the NOT EQUAL TO (<>) operator are not equal.


2 Answers

It seems too simple, but it looks like what you need:

SELECT id,question FROM `questions` 
WHERE `sort_order` > sort_order_variable
ORDER BY sort_order ASC 
LIMIT 1
like image 71
Eran Galperin Avatar answered Sep 28 '22 20:09

Eran Galperin


SELECT * FROM table_name WHERE sort_order > 5 ORDER BY sort_order ASC LIMIT 1
like image 32
Alexei Tenitski Avatar answered Sep 28 '22 18:09

Alexei Tenitski