Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using FIELD() in ORDER BY clause - MySQL

This is with reference to the answer given by Ayman Hourieh

to the question: MySQL - ORDER BY values within IN()

SELECT id, name
FROM mytable
WHERE name IN ('B', 'A', 'D', 'E', 'C')
ORDER BY FIELD(name, 'B', 'A', 'D', 'E', 'C')

The FIELD function returns the position of the first string in the remaining list of strings.

It will thus be something like .. ORDER BY 4 or ORDER BY 1 as the FIELD function returns the position. Please explain how does ORDER BY work in this situation.

like image 682
Manish Avatar asked Dec 02 '25 11:12

Manish


1 Answers

For each row, FIELD() returns an integer value. The rows are then ordered by this value.

Adding the FIELD() clause to the select part should help you understand how it works:

SELECT id, name, FIELD(name, 'B', 'A', 'D', 'E', 'C')
FROM mytable
WHERE name IN ('B', 'A', 'D', 'E', 'C')
ORDER BY FIELD(name, 'B', 'A', 'D', 'E', 'C')

Sample result set:

 4 | Z | 0
12 | B | 1
 1 | B | 1
 6 | A | 2
 3 | E | 4
like image 175
RandomSeed Avatar answered Dec 05 '25 00:12

RandomSeed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!