"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 SQL Results Based on WHERE IN Clause Order?

How to Order SQL Results Based on WHERE IN Clause Order?

Published on 2024-11-08
Browse:475

How to Order SQL Results Based on WHERE IN Clause Order?

Sorting Results According to WHERE IN Clause Order

When using the WHERE IN clause in SQL, the results are typically ordered by the column's natural ordering (usually ascending). However, in certain scenarios, you may prefer to have the rows returned in the same order as specified in the IN clause.

Solution: Ordering by Field

To sort rows according to the order specified in the WHERE IN clause, you can use the ORDER BY FIELD function. This function takes two arguments:

  • The column to sort by
  • A list of values representing the desired order

In this case, you can use the following query to sort the results by the ID column, in the order specified in the IN clause:

SELECT *
FROM table
WHERE id IN (118, 17, 113, 23, 72)
ORDER BY FIELD(id, 118, 17, 113, 23, 72);

This query will return the rows in the following order: 118, 17, 113, 23, 72.

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