Home >Database >Mysql Tutorial >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:
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:
<code class="sql">SELECT * FROM table WHERE id IN (118, 17, 113, 23, 72) ORDER BY FIELD(id, 118, 17, 113, 23, 72);</code>
This query will return the rows in the following order: 118, 17, 113, 23, 72.
The above is the detailed content of How to Order SQL Results Based on WHERE IN Clause Order?. For more information, please follow other related articles on the PHP Chinese website!