Home >Database >Mysql Tutorial >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:
ORDER BY sorts the rows:
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!