Monday, May 2, 2011

Creating Combined Queries in Oracle SQL

SQL queries are combined using the UNION operator. Using UNION, multiple SELECT statements can be specified, and their results can be combined into a single result set.

Using UNION
Using UNION is simple enough. All you do is specify each SELECT statement and place the keyword UNION between each.

Let's look at an example. You need a report on all your customers in Illinois, Indiana, and Michigan. You also want to include all Fun4All locations, regardless of state. Of course, you can create a WHERE clause that will do this, but this time you'll use a UNION instead.

As I just explained, creating a UNION involves writing multiple SELECT statements. First look at the individual statements:

SELECT cust_name, cust_contact, cust_email

FROM Customers

WHERE cust_state IN ('IL','IN','MI');


cust_name cust_contact cust_email

----------- ------------- ------------

Village Toys John Smith sales@villagetoys.com

Fun4All Jim Jones jjones@fun4all.com

The Toy Store Kim Howard NULL



Now Combne


SELECT cust_name, cust_contact, cust_email

FROM Customers

WHERE cust_state IN ('IL','IN','MI')

UNION

SELECT cust_name, cust_contact, cust_email

FROM Customers

WHERE cust_name = 'Fun4All';

cust_name cust_contact cust_email

--------- ------------ ----------

Fun4All Denise L. Stephens dstephens@fun4all.com

Fun4All Jim Jones jjones@fun4all.com

Village Toys John Smith sales@villagetoys.com

The Toy Store Kim Howard NULL