MySQL: sort selection in the order given in the IN clause

Question:

How do I select rows using the IN operator in the exact order in which they are passed? Those. SELECT id, name FROM users WHERE id IN (2, 3, 1)

Answer:

You can use the FIELD() function by passing it exactly the same sequence that you specify in IN . The function will return the index of the value in the sequence, and by it you can sort the selection with the ORDER BY construction.

SELECT
  id, name
FROM
  users
WHERE
  id IN (2, 3, 1)
ORDER BY
  FIELD(id, 2, 3, 1)
Scroll to Top