Home >Database >Mysql Tutorial >How Can I Prioritize a Specific Row and Then Order the Rest in MySQL?
Prioritization of MySQL result sets
In MySQL, you may need to retrieve data and have a specific item appear at the beginning of a list and then display the remaining items in a specific order. This can be achieved using the ORDER BY
clause.
To display one item first (here ID 5) and then sort the rest, you can use the following query:
<code class="language-sql">SELECT id, name FROM friends ORDER BY id = 5 DESC, id ASC;</code>
This query sorts the results in descending order based on the condition id = 5
. Therefore, rows with id = 5
will be placed at the beginning of the list, followed by the remaining rows in ascending order of their id
values.
Instructions:
ORDER BY
clause allows you to specify the sorting criteria for results. id = 5 DESC
Evaluates to TRUE if id
is equal to 5 and FALSE otherwise. Sorting this expression in descending order ensures that rows with id = 5
appear first because TRUE has higher precedence than FALSE. id ASC
sorts the remaining rows in ascending order based on their id
values. The above is the detailed content of How Can I Prioritize a Specific Row and Then Order the Rest in MySQL?. For more information, please follow other related articles on the PHP Chinese website!