Home > Database > Mysql Tutorial > How to Prioritize a Specific Item in MySQL Queries Then Sort the Rest?

How to Prioritize a Specific Item in MySQL Queries Then Sort the Rest?

Susan Sarandon
Release: 2025-01-24 09:37:10
Original
846 people have browsed it

How to Prioritize a Specific Item in MySQL Queries Then Sort the Rest?

MySQL Query: Prioritize Specific Items, Then Sort the Rest

This MySQL query prioritizes specific items in your results, displaying them first, followed by the remaining items sorted according to a chosen order.

Here's how to construct the query:

<code class="language-sql">SELECT id, name
FROM friends
ORDER BY 
    CASE 
        WHEN name = 'SpecificItemName' THEN 0  -- Prioritize 'SpecificItemName'
        ELSE 1                              -- All other items
    END,
    name ASC; -- Sort the remaining items alphabetically by name (adjust as needed)</code>
Copy after login

Replace 'SpecificItemName' with the actual name of the item you want to prioritize. The CASE statement assigns a value of 0 to the prioritized item and 1 to all others. The ORDER BY clause then sorts based on this value, placing the prioritized item first. The name ASC clause (or any other sorting criteria) sorts the remaining items alphabetically by name. You can change ASC to DESC for descending order, or replace name with another column for different sorting. This approach ensures that your specific item always appears at the top of the results, with the rest of the data organized as you specify.

The above is the detailed content of How to Prioritize a Specific Item in MySQL Queries Then Sort the Rest?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template