Explicitly specify sort order for MySQL query (use an “IN” list)
Question
With a query like the following, the default will return in order of id of least to greatest even if the IN
list is not in that order. In my situation the list will be supplied from some c# code.
How can I order the result set by the order of values in the IN
list?
What I have:
SELECT * FROM example Where Id in (1,3,2);
returns:
|---------------|---------------|
| id | Value |
|---------------|---------------|
| 1 | example1 |
|---------------|---------------|
| 2 | example2 |
|---------------|---------------|
| 3 | example3 |
|---------------|---------------|
What I want is:
SELECT * FROM example Where Id in (1,3,2)
Order By "Magic code here";
returns:
|---------------|---------------|
| id | Value |
|---------------|---------------|
| 1 | example1 |
|---------------|---------------|
| 3 | example3 |
|---------------|---------------|
| 2 | example2 |
|---------------|---------------|
Solution
You have two ways of doing this (see the fiddle here):
CREATE TABLE ex
(
id INTEGER AUTO_INCREMENT PRIMARY KEY,
value VARCHAR(10) NOT NULL
);
Populate the table:
INSERT INTO ex (value) VALUES
('example1'), ('example2'), ('example3');
And then the "magic sauce"...
SELECT * FROM ex ORDER BY field (id, 1, 3, 2);
Result:
id value
1 example1
3 example3
2 example2
This is a non-standard MySQL "trick".
A standards compliant way of doing this would be:
SELECT * FROM ex
ORDER BY
CASE id
WHEN 1 THEN 1
WHEN 2 THEN 3
WHEN 3 THEN 2
END;
Result:
id value
1 example1
3 example3
2 example2
See the PostgreSQL fiddle here. PostgreSQL is one of the (possibly the) most standards compliant RDBMS systems out there, so that's why I used it for comparison purposesl
p.s. welcome to the forum!
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange