Using an ORDER BY with a Compound Query

Team-Fly    

 
Sams Teach Yourself SQL in 24 Hours, Third Edition
By Ronald R. Plew, Ryan K. Stephens
Table of Contents
Hour  15.  Combining Multiple Queries into One


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 :

 graphics/syntax_icon.gif 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:

 graphics/mysql_icon.gif SELECT EMP_ID FROM EMPLOYEE_TBL UNION SELECT EMP_ID FROM EMPLOYEE_PAY_TBL ORDER BY 1; 
graphics/analysis_icon.gif

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.

graphics/note_icon.gif

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.

 graphics/mysql_icon.gif graphics/input_icon.gif  SELECT PROD_DESC FROM PRODUCTS_TBL   UNION   SELECT PROD_DESC FROM PRODUCTS_TBL   ORDER BY PROD_DESC;  graphics/output_icon.gif 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:

 graphics/mysql_icon.gif graphics/input_icon.gif  SELECT PROD_DESC FROM PRODUCTS_TBL   UNION   SELECT PROD_DESC FROM PRODUCTS_TBL;  graphics/output_icon.gif 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. 
graphics/note_icon.gif

The compound query operators covered in this hour are not currently supported in MySQL.



Team-Fly    
Top
 


Sams Teach Yourself SQL in 24 Hours
Sams Teach Yourself SQL in 24 Hours (5th Edition) (Sams Teach Yourself -- Hours)
ISBN: 0672335417
EAN: 2147483647
Year: 2002
Pages: 275

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net