Home > Ask the Oracle Database / Applications Experts > SQL Questions & Answers > How to sort an SQL UNION query with special ORDER BY sequence
Ask The Oracle Expert: Questions & Answers
EMAIL THIS

How to sort an SQL UNION query with special ORDER BY sequence

Rudy Limeback EXPERT RESPONSE FROM: Rudy Limeback

Pose a Question
Other Oracle Categories
Meet all Oracle Experts
Become an Expert for this site


Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us   


>
QUESTION POSED ON: 19 February 2009

I have the following query:

SELECT * FROM mytable WHERE col1 = 'c'
UNION
SELECT * FROM mytable WHERE col1 = 'a'
UNION
SELECT * FROM mytable WHERE col1 = 'd'
UNION
SELECT * FROM mytable WHERE col1 = 'b'

How can I get the result in the same sequence of select queries rather than getting sorted by col1? i.e. I need the result to appear in this sequence: c,a,d,b.



Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us   



RELATED CONTENT
SQL
How to check SQL query construction with the Mimer Validator
Using the SQL GROUP BY clause for counting combinations
How to use an SQL CASE expression
How to use string functions to make an SQL join
An SQL solution for a customer order homework problem
How to use SQL's POSITION function with substrings
Using SQL date functions to get totals for last three days
Using CASE in the SQL ORDER BY clause
What's the difference between an SQL inner join and equijoin?
Using the SQL date function to find aggregate totals by month

Oracle and SQL
Oracle tutorial library: SearchOracle.com's learning guides
Can I specify Oracle column order in my database table?
Review: Oracle's 11g R2 database has some good and bad
SELECT statement syntax and examples
Oracle PL/SQL tutorial
PL/SQL datatypes in Oracle
Stored procedures in PL/SQL
PL/SQL functions and triggers in Oracle
Do I need a license for SQL Developer Data Modeler in Oracle?
Using the SQL GROUP BY clause for counting combinations
Oracle and SQL Research

RELATED GLOSSARY TERMS
Terms from Whatis.com − the technology online dictionary
autonomous transaction  (SearchOracle.com)
CFML  (SearchOracle.com)
dynamic SQL  (SearchOracle.com)
foreign key  (SearchOracle.com)
Java Database Connectivity  (SearchOracle.com)
Open Database Connectivity  (SearchOracle.com)
Oracle  (SearchOracle.com)
stored procedure  (SearchOracle.com)
The Open Group  (SearchOracle.com)

RELATED RESOURCES
2020software.com, trial software downloads for accounting software, ERP software, CRM software and business software systems
Search Bitpipe.com for the latest white papers and business webcasts
Whatis.com, the online computer dictionary


In the execution of an SQL query, the ORDER BY clause is done last. Like the old saying goes, "It's all over but the sorting." The database server has retrieved table rows, joined them together as necessary, filtered and grouped them if required and the results are now to be sorted.

Some database developers believe that sorting should be done in the application server, not in the database server. They have a very good point. Sometimes, the presence of an ORDER BY clause requires the database server to write the results into a temporary table, and this temporary table is then read back and sorted. Managing temporary tables consumes very costly database server cycles, whereas letting the application server do it would be cheaper and probably faster. A centralized resource such as a database server should never be squandered on tasks best done elsewhere.

Now consider this UNION query. Whether we do the sorting with the ORDER BY clause or in the application, we still need an algorithm, a method, to determine the sort order. We need our logic to do the following: if the value in col1 is 'c', then these rows go first; if the value in col1 is 'a', then these go second; and so on. This is quite easy to do in a UNION query:

SELECT * , 1 FROM mytable WHERE col1 = 'c'
UNION
SELECT * , 2 FROM mytable WHERE col1 = 'a'
UNION
SELECT * , 3 FROM mytable WHERE col1 = 'd'
UNION
SELECT * , 4 FROM mytable WHERE col1 = 'b'

Can you see how that's going to work? Each row gets an extra column, a number, and the results will be sorted based on the values of these numbers. Thus the rows will be sorted into the desired, special sequence. We could now either add the ORDER BY clause to the SQL statement, or return the results to the application and let it do the sorting.

The application would need to know which column to sort on, so it's a good idea to name the column:

SELECT * , 1 AS sortcol
             FROM mytable WHERE col1 = 'c'
UNION
SELECT * , 2 FROM mytable WHERE col1 = 'a'
UNION
SELECT * , 3 FROM mytable WHERE col1 = 'd'
UNION
SELECT * , 4 FROM mytable WHERE col1 = 'b'

Result set column names for a UNION query are taken from the first SELECT in the UNION, so it's not necessary to assign the column alias in the other SELECTs.

And now for something completely different:

SELECT *
     , CASE WHEN col1 = 'c' THEN 'Curly'
            WHEN col1 = 'a' THEN 'Larry'
            WHEN col1 = 'd' THEN 'Moe'
            WHEN col1 = 'b' THEN 'Shemp'
        END AS sortcol
  FROM mytable
 WHERE col1 IN ( 'c','a','d','b' )

This is possible only, of course, because all four original SELECTs retrieved rows from the same table. If there were four different tables, then we would have to use the UNION. Here, we have only one SELECT against the table. The CASE expression takes only a few extra nanoseconds to evaluate, compared with no evaluation for hardcoded values. However, four SELECTs, even though it's the same table, might actually get executed as four passes against the data. Most optimizers would spot this, but why give them a chance to go wrong.

And yes, I could have assigned numbers as THEN values in the CASE expression. Sorting a VARCHAR(5) column might be marginally slower than sorting 1-byte numbers (although the difference is likely not noticeable), but I think the names are pretty neat.




Search and Browse the Expert Answer Center
Search and browse more than 25,000 question and answer pairs from more than 250 TechTarget industry experts.
Browse our Expert Advice



Oracle White Papers: Fusion Middleware
HomeNewsTopicsTipsAsk the ExpertsMultimediaWhite PapersProductsBlogs
About Us  |  Contact Us  |  For Advertisers  |  For Business Partners  |  Site Index  |  RSS
SEARCH 
TechTarget provides technology professionals with the information they need to perform their jobs - from developing strategy, to making cost-effective purchase decisions and managing their organizations' technology projects - with its network of technology-specific websites, events and online magazines.

TechTarget Corporate Web Site  |  Media Kits  |  Site Map




All Rights Reserved, Copyright 2003 - 2009, TechTarget | Read our Privacy Policy
  TechTarget - The IT Media ROI Experts