Home > Database > Mysql Tutorial > How to Prioritize Specific Rows in Database Queries?

How to Prioritize Specific Rows in Database Queries?

Mary-Kate Olsen
Release: 2024-12-30 05:32:09
Original
976 people have browsed it

How to Prioritize Specific Rows in Database Queries?

Returning Rows with a Specific Value First

In certain database queries, it can be desirable to prioritize the display of rows containing a specific value. For example, consider the following table:

Table: Users

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

If we wish to retrieve the rows where the city column contains "New York" first, and then the remaining rows in alphabetical order of the city, we can utilize the following query:

SQL Server, Oracle, and DB2:

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

This query employs a CASE expression to assign a priority of 1 to rows with "New York" as the city value and a priority of 2 otherwise. The ORDER BY clause then uses this priority along with the city column for sorting. Consequently, the rows with "New York" will be returned first, followed by the rest of the rows ordered alphabetically by city.

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