Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL 'IN' clause and the returned record set order

Tags:

sql

mysql

For example: select * from T where T.id IN(4,78,12,45)

I want the returned record set just order by the position in the 'IN' clause. How can I do this?

like image 561
lovespring Avatar asked Sep 03 '09 11:09

lovespring


People also ask

Which clause of MySQL helps to arrange records in an order?

The MySQL ORDER BY Keyword The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

Is ORDER BY a clause in MySQL?

Answer: ORDER BY is a clause that is typically used along with SELECT queries in MySQL and is used to return the result set sorted in the given order against the given column or field in the table.

How do I change the order of rows in MySQL?

An "ALTER TABLE ORDER BY" statement exist in the syntaxes accepted by MySQL. According to the documentation, this syntax: - only accept *one* column, as in "ALTER TABLE t ORDER BY col;" - is used to reorder physically the rows in a table, for optimizations.

Which clause is used to sort data in MySQL?

The ORDER BY clause is used to sort the result-set in ascending or descending order.


2 Answers

You could do it using FIND_IN_SET, e.g.

SELECT * FROM T WHERE T.id IN(4,78,12,45)
ORDER BY FIND_IN_SET(T.id,'4,78,12,45');

While you do have to duplicate the list, if you're generating the query in code this isn't a huge problem.

like image 140
Paul Dixon Avatar answered Sep 18 '22 23:09

Paul Dixon


In the general case, you can't. SQL doesn't guarantee order unless you use the ORDER BY clause, and it can't be tied into the contents of an IN statement.

However, if you can build a temporary table that orders the values you're selecting from, you can join on that table and order by it.

For example, you have a temporary table that contains something like the following:

id  | order
----+------
4   | 1
78  | 2
12  | 3
45  | 4

Then you can order it like this:

SELECT T.*
FROM T
INNER JOIN temp
ON T.id = temp.id
ORDER BY temp.order ASC
like image 37
Welbog Avatar answered Sep 21 '22 23:09

Welbog