tags:

views:

97

answers:

2

I have to write a drop down query for countries. But USA should always be first. The rest of the countries are in alphabetical order I tried the following query

SELECT      
           countries_id
        ,countries_name

        FROM get_countries
        WHERE 
             countries_id = 138
        UNION 

        SELECT 
                countries_id
              ,countries_name

         FROM get_countries 
        WHERE   
                  countries_id != 138
        ORDER BY 2 ASC
+3  A: 

Something like this maybe:

ORDER BY
  CASE 
     WHEN upper(country_name) = 'USA' then '0'
     ELSE lower(country_name)
  END

Here's a complete example

create TABLE countries (country_name VARCHAR2(50));

INSERT INTO countries VALUES ('USA');
INSERT INTO countries VALUES ('India');
INSERT INTO countries VALUES ('Russia');
INSERT INTO countries VALUES ('China');
COMMIT;

SELECT country_name
  FROM countries
ORDER BY
  CASE 
     WHEN upper(country_name) = 'USA' then '0'
     ELSE lower(country_name)
  END

Returns:

USA
China
India
Russia
dcp
ORDER BY CASE WHEN upper(country_name) = 'USA' then '0' ELSE lower(country_name) ASC END
Robert
it is throwing an Error Missing keyword
Robert
@Robert - see my complete example above, I just tested it on Oracle 10g and it worked fine.
dcp
Thank you very much! you are absolutely correct.Now was wondering will this CASE/WHEN/ELSE effect the speed of the query?
Robert
@Robert - You should have an index on country_name (or countries_name in your table) so the sort can be done efficiently. Speed should be ok, but you can always test it yourself and run explain plan to see the query plan if performance turns out to be bad for some reason.
dcp
If you want to avoid a sort by using an index, an ordinary index on country_name will not cut it. You'd need a function-based index - over the whole CASE..END expression.
Jeffrey Kemp
A: 

It's been a while since I worked with oracle, but you can try ORDER BY countries_name = 'USA', countries_name ASC.

Correction

Sorry that didn't work. I had "countries_name" mis-typed as "country_name", so it may work now.

You could also use ORDER BY decode(countries_name, 'USA', 0, 1), countries_name ASC.

Jon
@Jon - Using that gives a syntax error when run on Oracle 10g.
dcp
YEP "Decode" works Thanks Jon.
Robert