Skip to content
Advertisement

Order SQL results with sticky item

Is there a way to order results alphabetically and by country code, but making one result stick at the top for each country code?

For example, this order:

ORDER BY PortalStock.CountryCode DESC, PortalStock.Location ASC";

would currently display as;

Location    CountryCode
LONDON      GB
OXFORD      GB
READING     GB
LYON        FR
MARSEILLE   FR
PARIS       FR
RENNES      FR

I’d like to be able to order the results first by country (GB first), then for GB have Oxford at the top of the list, with any additional result being alphabetical.

The FR results should start with Paris, also with any additional result being alphabetical.

Location    Country
OXFORD      GB
LONDON      GB
READING     GB
PARIS       FR
LYON        FR
MARSEILLE   FR
RENNES      FR

Is this a possibility without further order data being added to the DB?

Advertisement

Answer

You want conditional order by :

order by country desc,
         (case when location = 'oxford' then 1 else 2 end), 
          location;

If you want oxford at top for only GB country then add one more condition :

(case when country = 'GB' and location = 'oxford' then 1 else 2 end)

Note : This will first desc by country not only for GB & then sort first oxford location.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement