Union operator is used to merge the records from first table with the records from the second table.
Some conditions:
1. It's used to fetch the records from two or more tables into a single result set.
2. The union columns should be of same data type.
3. Union operator will remove the duplicates from the result set.
Am trying to put union between the tables with same column types,
drop table venkat1
create table venkat1(id int, rating int, dat datetime,auditrecord int)
insert into venkat1 values(1,1,'7/1/2006',1)
insert into venkat1 values(1,3,'7/1/2006',2)
insert into venkat1 values(1,5,'7/2/2006',3)
insert into venkat1 values(1,2,'8/10/2006',4)
insert into venkat1 values(2,4,'8/7/2006',1)
select * from venkat1
create table venkat2(id int, rating int)
insert into venkat2 values(6,1)
insert into venkat2 values(7,3)
insert into venkat2 values(8,5)
insert into venkat2 values(9,2)
select * from venkat2
select id,rating from venkat1
union
select id,rating from venkat2
Everything seems to be fine. Now, am trying with bit different data type.. replacing integer column with varchar column. Let's see what's happening.
drop table venkat2
create table venkat2(id int, rating decimal(5,2))
insert into venkat2 values(6,1)
insert into venkat2 values(7,3)
insert into venkat2 values(8,5)
insert into venkat2 values(9,2)
select * from venkat2
select id,rating from venkat1
union
select id,rating from venkat2
OOPS, no error instead the entire result set will be associated with decimal column.
By execution, the result set will be taking the highest refining column type to accomodate both
the data types. Nice to see...
create table venkat2(id int, rating varchar(10))
insert into venkat2 values(6,'Number 1')
insert into venkat2 values(7,'Number 3')
insert into venkat2 values(8,'Number 5')
insert into venkat2 values(9,'Number 2')
select id,rating from venkat1
union
select id,rating from venkat2
We are getting an error,
Conversion failed when converting the varchar value 'Number 1' to data type int.
Checking for the unique property of the union operator:
I have added a new row, which has duplicate record and am doing an union operator.
drop table venkat2
create table venkat2(id int, rating decimal(5,2))
insert into venkat2 values(6,1)
insert into venkat2 values(7,3)
insert into venkat2 values(8,5)
insert into venkat2 values(9,2)
insert into venkat2 values(9,2)
select id,rating from venkat1
union
select id,rating from venkat2
Here comes the difference between the above two, Union all will give all the records including duplicates whereas union operator will remove the duplicates.
Thanks and Regards,
Venkatesan Prabu .J
No comments:
Post a Comment