10.12.2012 Views

Application Programming and SQL Guide - Kmlinux

Application Programming and SQL Guide - Kmlinux

Application Programming and SQL Guide - Kmlinux

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Merging lists of values: UNION<br />

Using the UNION keyword, you can combine two or more SELECT statements to<br />

form a single result table. When DB2 encounters the UNION keyword, it processes<br />

each SELECT statement to form an interim result table, <strong>and</strong> then combines the<br />

interim result table of each statement. If you use UNION to combine two columns<br />

with the same name, the result table inherits that name.<br />

When you use the UNION statement, the <strong>SQL</strong>NAME field of the <strong>SQL</strong>DA contains<br />

the column names of the first oper<strong>and</strong>.<br />

Using UNION to eliminate duplicates<br />

You can use UNION to eliminate duplicates when merging lists of values obtained<br />

from several tables.<br />

Example: UNION clause: You can obtain a combined list of employee numbers<br />

that includes both of the following:<br />

v People in department D11<br />

v People whose assignments include projects MA2112, MA2113, <strong>and</strong> AD3111.<br />

The following <strong>SQL</strong> statement gives a combined result table containing employee<br />

numbers in ascending order with no duplicates listed:<br />

SELECT EMPNO<br />

FROM DSN8810.EMP<br />

WHERE WORKDEPT = ’D11’<br />

UNION<br />

SELECT EMPNO<br />

FROM DSN8810.EMPPROJACT<br />

WHERE PROJNO = ’MA2112’ OR<br />

PROJNO = ’MA2113’ OR<br />

PROJNO = ’AD3111’<br />

ORDER BY EMPNO;<br />

If you have an ORDER BY clause, it must appear after the last SELECT statement<br />

that is part of the union. In this example, the first column of the final result table<br />

determines the final order of the rows.<br />

Using UNION ALL to keep duplicates<br />

If you want to keep duplicates in the final result table of a UNION, specify the<br />

optional keyword ALL after the UNION keyword.<br />

Example: UNION ALL clause: The following <strong>SQL</strong> statement gives a combined<br />

result table containing employee numbers in ascending order, <strong>and</strong> includes<br />

duplicate numbers:<br />

SELECT EMPNO<br />

FROM DSN8810.EMP<br />

WHERE WORKDEPT = ’D11’<br />

UNION ALL<br />

SELECT EMPNO<br />

FROM DSN8810.EMPPROJACT<br />

WHERE PROJNO = ’MA2112’ OR<br />

PROJNO = ’MA2113’ OR<br />

PROJNO = ’AD3111’<br />

ORDER BY EMPNO;<br />

Chapter 1. Retrieving data 13

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!