Union: Course Materials May Not Be Reproduced in Whole or in Part Without The Prior Written Permission of IBM
Union: Course Materials May Not Be Reproduced in Whole or in Part Without The Prior Written Permission of IBM
Copyright IBM Corporation 2007 Course materials may not be reproduced in whole or in part without the prior written permission of IBM.
4.0.3 3.3.1
Unit Objectives
After completing this unit, you should be able to: Produce a single result table containing data from more than one query State the UNION rules State the difference between UNION and UNION ALL
MGRNO , 'Dept.:', DEPTNAME AS NAME FROM DEPARTMENT WHERE MGRNO IS NOT NULL UNION ALL SELECT MGRNO, 'Mgr.:', LASTNAME AS NAME FROM DEPARTMENT D, EMPLOYEE E WHERE D.MGRNO = E.EMPNO ORDER BY 1,2 DESC
NAME HAAS SPIFFY COMPUTER SERVICE DIV. THOMPSON PLANNING KWAN INFORMATION CENTER GEYER SUPPORT SERVICES
EDLEVEL 18 18 18 18
EDLEVEL 16 18 18 18 18 18
UNION
SELECT FROM WHERE LASTNAME, EDLEVEL EMPLOYEE JOB = 'ANALYST' LASTNAME NICHOLLS QUINTANA EDLEVEL 18 16
EDLEVEL 18 18 18 18
EDLEVEL 18 18 18 16 18
M.L
LASTNAME, EDLEVEL SELECT EMPLOYEE FROM JOB = 'ANALYST' WHERE INTERSECT LASTNAME, EDLEVEL SELECT EMPLOYEE FROM EDLEVEL = 18 WHERE
LASTNAME NICHOLLS
EDLEVEL 18
Checkpoint
1. True or False? The results of arbitrary SELECTs can be combined by means of UNION and ordered to get a new result. 2. Why or when should you use UNION?
a. When all duplicate rows have to be eliminated. b. When SELECTs with an arbitrary number of columns should be combined.
Checkpoint Solutions
1. False. The SELECTs must follow very strict UNION rules. 2. a 3. Equal number of columns. Compatible data types. ORDER BY must be the last clause. In the ORDER BY clause, numbers must be used when the column being sorted does not have the same name in all SELECTs.
Unit Summary
Having completed this unit, you should be able to: Produce a single result table containing data from more than one query State the UNION rules State the difference between UNION and UNION ALL