Wednesday, October 20, 2021

MySQL: Sorting query result with conditions

Use MySQL CASE function to first sort result into 3 sets, then sort them by columns:

SELECT City, Country FROM Customers
WHEN Country LIKE 'U%' THEN 1
WHEN Country LIKE 'S%' THEN 2
END), Country, City;

The output will be:

    City    Country
    Cowes    UK
    London    UK
    London    UK
    Albuquerque    USA
    Anchorage    USA
    Boise    USA
    Butte    USA
    Elgin    USA
    Barcelona    Spain
    Madrid    Spain
    Sevilla    Spain
    Bräcke    Sweden
    Luleå    Sweden
    Bern    Switzerland
    Genève    Switzerland
    Graz    Austria
    Salzburg    Austria
    Bruxelles    Belgium
    Charleroi    Belgium
    Montréal    Canada
    Tsawassen    Canada
    Vancouver    Canada
    Aachen    Germany
    Mannheim    Germany
    Stuttgart    Germany
    Barquisimeto    Venezuela
    Caracas    Venezuela

No comments:

Get This <