Introduction to FIELD function: FIELD(str, str1, str2, str3, …) function search for ‘str’ in the list ‘str1,str2,str3…’ and returns the index (position) of str in the list. Example: Use of FIELD function in ORDER BY clause:
|
Simple order by example:
SELECT id, name FROM color ORDER BY id; Output: +——+——–+
| id | name | +——+——–+ | 1 | White | | 2 | Black | | 3 | Yellow | | 4 | Green | | 5 | Red | | 6 | Orange | +——+——–+
Same query with use of FIELD function
SELECT id, name FROM color ORDER BY FIELD(name, ‘Red’, ‘Green’, ‘Orange’, ‘White’, ‘Yellow’, ‘Black’); Output: +——+——–+
| id | name | +——+——–+ | 1 | White | | 2 | Black | | 3 | Yellow | | 4 | Green | | 5 | Red | | 6 | Orange | +——+——–+ NOTE: If there are values which is present in the table but not passed to the FIELD function, then they will appear towards the end of the output in random order. |