AfricaDotNet
www.AfricaDotNet.com Continues the .NET Conversation in Africa

How to use SQL UNION Operator

rated by 0 users
This post has 1 Reply | 2 Followers

Top 25 Contributor
Posts 1
benmute Posted: 04-16-2009 7:09 AM

The UNION Operator is used to connect the result set of two or more SELECT statements. The SELECT  statements should have the same number of columns and the columns should have similar data types in the same order. There is a difference between UNION and UNION ALL.

While UNION ALL returns all the rows including duplicate rows, UNION returns only one row where a row appears more than once in a resultset.

Example:

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

SELECT ColA, ColB, ColC From Table1

UNION

SELECT Col1, Col2, Col3 FROM Table2

OR

SELECT ColA, ColB, ColC From Table1

UNION ALL

SELECT Col1, Col2, Col3 FROM Table2

 

Top 10 Contributor
Male
Posts 22

a common gotcha is how to order the records.

SELECT ColA AS Colname, ColB, ColC From Table1

UNION ALL

SELECT Col1 AS Colname, Col2, Col3 FROM Table2

ORDER BY Colname

it kinda looks out of place but it is the correct way to do stuff.

 

also

for large sets of data i.e. millions or rows use of distinct will cost you

select distinct * from table is very expensive

use group by or even a sub-query for performance enhancement.

 

Page 1 of 1 (2 items) | RSS
(c) AfricaDotNet
Powered by Community Server (Non-Commercial Edition), by Telligent Systems