Home >Database >Mysql Tutorial >How Can I Prioritize a Specific Row and Then Order the Rest in MySQL?

How Can I Prioritize a Specific Row and Then Order the Rest in MySQL?

DDD
DDDOriginal
2025-01-24 09:26:10709browse

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:

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

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