Home  >  Article  >  Database  >  How to Order SQL Results Based on WHERE IN Clause Order?

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

Susan Sarandon
Susan SarandonOriginal
2024-10-26 12:09:29154browse

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:

<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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn