Home >Database >Mysql Tutorial >How to Prioritize Rows with a Specific Value in SQL Queries?

How to Prioritize Rows with a Specific Value in SQL Queries?

Linda Hamilton
Linda HamiltonOriginal
2025-01-05 05:01:09764browse

How to Prioritize Rows with a Specific Value in SQL Queries?

Return Rows with a Specific Value First

You need to modify your query to prioritize rows based on a specific column value while maintaining alphabetical order for the remaining rows.

To achieve this:

SQL Server, Oracle, DB2, and Others

Use the following syntax:

ORDER BY CASE WHEN city = 'New York' THEN 1 ELSE 2 END, city

In this code:

  • CASE statement creates a priority column:

    • If city equals 'New York', the priority is 1.
    • Otherwise, the priority is 2.
  • ORDER BY sorts the rows:

    • First, based on the priority (rows with 'New York' come first).
    • Then, alphabetically by the city column.

Example

Using the provided table, this query:

SELECT *
FROM Users
ORDER BY CASE WHEN city = 'New York' THEN 1 ELSE 2 END, city;

will return the following results:

 - id - name -  city
 - 3    John    New York
 - 4    Amy     New York
 - 6    Nick    New York
 - 1    George  Seattle
 - 2    Sam     Miami
 - 5    Eric    Chicago

This query effectively returns rows with 'New York' first, then alphabetizes the remaining rows by city.

The above is the detailed content of How to Prioritize Rows with a Specific Value in SQL Queries?. 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