"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Order MySQL Results by IN() Clause Order using the FIELD Function?

How to Order MySQL Results by IN() Clause Order using the FIELD Function?

Posted on 2025-03-22
Browse:244

How to Order MySQL Results by IN() Clause Order using the FIELD Function?

Using FIELD Function to Order Results by IN() Order

In MySQL, the ORDER BY clause can be used to sort query results in ascending or descending order. When using the IN() method, it can be difficult to ensure that the results are returned in the same order as the IDs in the IN() clause. Fortunately, there is a solution: the FIELD function.

The FIELD function takes two parameters: a field name and a list of values. It returns the index of the first value in the list that matches the field value. For example, the following query would return the values 1, 2, 3, for the column "id" for rows where the value is 3, 2, or 1:

SELECT id, FIELD(id, 3, 2, 1) AS ordering FROM table_name;

To order the results by the IN() order, simply pass the IN() clause values as the second parameter to the FIELD function:

SELECT id, FIELD(id, 4, 7, 3, 8, 9) AS ordering FROM table_name;

This will return the results in the order specified:

4 - Article 4
7 - Article 7
3 - Article 3
8 - Article 8
9 - Article 9
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3