Home page
 
 Home 
 ASP 
 PHP 
 SQL 
 HTML 
 JavaScript 
 Search 
 Contact 
 
Search
or browse popular tags
Got questions?

We got answers.

Ask your question about PHP, ASP, Javascript, HTML, CSS, hosting and get professional help, free of charge.

Subscription

Sign up for the free email newsletter for new tips, tutorials and more. Enter your email address below, and then click the button.

Privacy Policy

RSS Twitter

SQL: Union Clause

Print Bookmark and Share

The Union clause allows you to combine the result sets of 2 or more individual queries. Union differs from subqueries in that it is made up of queries that are independent from each other. UNION combines the output of these individual Selects and lists them as a part of a single output table.

The syntax for a Union clause is as follows:

SELECT column1, ... column_n
FROM derived_table
UNION [ALL]
SELECT column1, ... column_n
FROM derived_table

Each SQL statement within the Union query must have the same number of fields in the result sets with similar data types. Also, when using Union, only distinct values are selected (similar to Select Distinct).

Example #1

SELECT Item
FROM Antiques
UNION
SELECT ItemDesired
FROM Orders

In this example, if an item appeared in both the Antiques and Orders table, it would appear once in your result set.

Example #2

SELECT FirstName, LastName
FROM EmployeeAddressTable
WHERE City IN ('Losantiville','Paris')
UNION SELECT OwnerFirstName,OwnerLastName
FROM AntiqueOwners
WHERE City IN ('Losantiville','Paris','San Diego')

This example takes certain selected fields from the 'AntiqueOwners' table and joins them onto the end of the same number of selected fields from the 'EmployeeAddressTable' table. The query will return all employees living in Losantiville or Paris and all AntiqueOwners living in Losantiville, Paris or San Diego.


If you'd like to see how it works, enter SQL statement and press Execute
 

Free Contact Form

Need help with ASP, PHP, Javascript?

Let our experts help you.
 
 
PHPRunner. Build great looking PHP+MySQL web sites with no programming
Web hosting from $5/month (PHP,ASP,MySQL,unlimited emails)



Tags: SQL UNION QUERY COMBINE RESULTS SELECT

Add To: Add to dzone dzone | Digg this digg | Add to del.icio.us del.icio.us | Stumble it stumbleupon

  • Comments (1)





Copyright © 2005-2009             www.WebCheatSheet.com All Rights Reserved.