Conditional Sorting in an SQL Query

I had the need to create a sorted list using SQL. However, the user wanted one particular set of items to appear at the top of the list, out of the default collating sequence.

Fortunately, this can be easily done by using a CASE construct within the ORDER BY clause:

SELECT first_name
       , last_name
       , city
FROM   customers
              WHEN 'VICTORIA' THEN 'a'
              ELSE city
            END )
          , last_name
          , first_name;  

This query will show customers sorted by city, then by name, but will list customers who live in Victoria first (which is only fair and appropriate).


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s