Search This Blog

Wednesday, March 20, 2013

Union SQL Server

SQL Server > Operators > Union

Union combines the results of queries into a single result set.

The number of the columns must be the same in all queries.
The data types must be compatible.

All incorporates all rows into the results and includes duplicates. If not specified, duplicate rows are removed.

Example

create table #t(name varchar(50))
insert into #t(name) values ('1')
insert into #t(name) values ('2')
insert into #t(name) values ('3')

create table #t1(name varchar(50))
insert into #t1(name) values ('1')
insert into #t1(name) values ('4')
insert into #t1(name) values ('5')

select * from #t
union
select * from #t1

Result:
name
1
2
3
4
5

select * from #t
union all

select * from #t1

Result:
name
1
2
3
1
4
5