Home >Database >Mysql Tutorial >How to Prioritize a Specific Item in MySQL Sort Results?
Specific items are prioritized in MySQL sort results
In SQL data retrieval, we often encounter scenarios where we need to prioritize specific items at the top of the results while sorting the remaining elements. This is useful when we need to prioritize specific items or maintain the expected order of data.
This article will use an example to demonstrate how to achieve this goal in MySQL 5.1.x. Let's say we have a table called "friends" with the following columns:
Suppose we want to get all friends from the table and make sure the friend with id 5 is shown at the first position in the list. We don't care about the order of other friends.
To achieve this we can use the following MySQL query:
<code class="language-sql">SELECT id, name FROM friends ORDER BY id = 5 DESC, id ASC;</code>
This query retrieves all friends, but it uses the ORDER BY
clause to put the friend with id 5 at the top of the list. DESC
The keyword specifies that the results should be sorted in descending order, effectively putting the item with id 5 first. id ASC
Make sure the remaining items are in ascending order.
With this approach, we can easily prioritize a specific item when retrieving data from the table, ensuring it appears first while maintaining the expected order of the rest of the results.
The above is the detailed content of How to Prioritize a Specific Item in MySQL Sort Results?. For more information, please follow other related articles on the PHP Chinese website!