Sybase Technical Library - Product Manuals Home
[Search Forms] [Previous Section with Hits] [Next Section with Hits] [Clear Search] Expand Search

Summarizing
groups of data: the compute clause [Table of Contents] Chapter 4 Joins: Retrieving Data from Several
Tables

Transact-SQL User's Guide

[-] Chapter 3 Using Aggregates, Grouping, and Sorting
[-] Combining queries: the union operator

Combining queries: the union operator

The union operator combines the results of two or more queries into a single result set. The Transact-SQL extension to union allows you to:

The syntax of the union operator is as follows:

query1
     [union [all] queryN ] ... 
     [order by clause] 
     [compute
clause]

where query1 is:

select select_list[into clause]
[from clause]
[where clause]
[group by clause]
[having clause]

and queryN is:

select select_list[from clause]
[where clause]
[group by clause]
[having clause]

Figure 3-1: Union combining queriesraster

For example, suppose you have the following two tables containing the data shown:

The following query creates a union between the two tables:

create table T1 (a char(4), b int)
insert T1 values ("abc", 1)
insert T1 values ("def", 2)
insert T1 values ("ghi", 3)
create table T2 (a char(4), b int)
insert T2 values ("ghi", 3)
insert T2 values ("jkl", 4)
insert T2 values ("mno", 5)
select * from T1 
union 
select * from T2 
a     b
----  --------- 
abc           1 
def           2 
ghi           3 
jkl           4 
mno           5 
 
(5 rows affected)

By default, the union operator removes duplicate rows from the result set. Use the all option to include duplicate rows. Notice also that the columns in the result set have the same names as the columns in T1. You can use any number of union operators in a Transact-SQL statement. For example:

x union y union z 

By default, Adaptive Server evaluates a statement containing union operators from left to right. You can use parentheses to specify a different evaluation order.

For example, the following two expressions are not equivalent:

x union all (y union z)

(x union all y) union z 

In the first expression, duplicates are eliminated in the union between y and z. Then, in the union between that set and x, duplicates are not eliminated. In the second expression, duplicates are included in the union between x and y, but are then eliminated in the subsequent union with z; all does not affect the final result of this statement.

Guidelines for union queries

When you use union statements:

Using union with other Transact-SQL commands

When you use union statements with other Transact-SQL commands:


Summarizing
groups of data: the compute clause [Table of Contents] Chapter 4 Joins: Retrieving Data from Several
Tables