The ORDER BY clause can be used with a compound query. However, the ORDER BY can only be used to order the results of both queries. Therefore, there can be only one ORDER BY clause in a compound query, even though the compound query may consist of multiple individual queries or SELECT statements. The ORDER BY must reference the columns being ordered by an alias or by the number of column order.
The syntax is as follows:
SELECT COLUMN1 [, COLUMN2 ] FROM TABLE1 [, TABLE2 ] [ WHERE ] OPERATOR{UNION | EXCEPT | INTERSECT | UNION ALL} SELECT COLUMN1 [, COLUMN2 ] FROM TABLE1 [, TABLE2 ] [ WHERE ] [ ORDER BY ]
Examine the following example:
SELECT EMP_ID FROM EMPLOYEE_TBL UNION SELECT EMP_ID FROM EMPLOYEE_PAY_TBL ORDER BY 1;
The results of the compound query are sorted by the first column of each individual query. Duplicate records can easily be recognized by sorting compound queries.
Note
The column in the ORDER BY clause is referenced by the number 1 instead of the actual column name.
The preceding SQL statement returns the employee ID from the EMPLOYEE_TBL and the EMPLOYEE_PAY_TBL, but does not show duplicates and orders by the employee ID.
The following example shows the use of the ORDER BY clause with a compound query. The column name can be used in the ORDER BY clause if the column sorted by has the same name in all individual queries of the statement.
SELECT PROD_DESC FROM PRODUCTS_TBL UNION SELECT PROD_DESC FROM PRODUCTS_TBL ORDER BY PROD_DESC;
PROD_DESC ----------------------- ASSORTED COSTUMES ASSORTED MASKS CANDY CORN FALSE PARAFFIN TEETH KEY CHAIN LIGHTED LANTERNS OAK BOOKSHELF PLASTIC PUMPKIN 18 INCH PLASTIC SPIDERS PUMPKIN CANDY WITCHES COSTUME 11 rows selected.
The following query uses a numeric value in place of the actual column name in the ORDER BY clause:
SELECT PROD_DESC FROM PRODUCTS_TBL UNION SELECT PROD_DESC FROM PRODUCTS_TBL ORDER BY 1;
PROD_DESC ----------------------- ASSORTED COSTUMES ASSORTED MASKS CANDY CORN FALSE PARAFFIN TEETH KEY CHAIN LIGHTED LANTERNS OAK BOOKSHELF PLASTIC PUMPKIN 18 INCH PLASTIC SPIDERS PUMPKIN CANDY WITCHES COSTUME 11 rows selected.