How does ORDER BY FIELD() in MySQL work internally
64
votes
2
answers
217666
views
I understand how
ORDER BY
clause works and how the FIELD()
function works.
What i want to understand is how the both of them work together to sort.
How are the rows retrieved and how is the sort order derived
+----+---------+
| id | name |
+----+---------+
| 1 | stan |
| 2 | kyle |
| 3 | kenny |
| 4 | cartman |
+----+---------+
SELECT * FROM mytable WHERE id IN (3,2,1,4) ORDER BY FIELD(id,3,2,1,4)
The query above will result in
+----+---------+
| id | name |
+----+---------+
| 3 | kenny |
| 2 | kyle |
| 1 | stan |
| 4 | cartman |
+----+---------+
something similar to saying ORDER BY 3, 2, 1, 4
QUESTIONS
- How does this work internally?
- How does MySQL get the rows, and calculate the sort order ?
- How does MySQL know it has to sort by the id column ?
Asked by itz_nsn
(806 rep)
Aug 5, 2015, 07:52 PM
Last activity: Sep 18, 2021, 01:27 PM
Last activity: Sep 18, 2021, 01:27 PM