SQL supports few Set operations to be performed on table data. These are used to get meaningful results from data, under different special conditions.

Union

UNION is used to combine the results of two or more Select statements. However it will eliminate duplicate rows from its result set. In case of union, number of columns and datatype must be same in both the tables.
union in sql

Example of UNION

The First table,
IDName
1abhi
2adam
The Second table,
IDName
2adam
3Chester
Union SQL query will be,
select * from First
UNION
select * from second 
The result table will look like,
IDNAME
1abhi
2adam
3Chester

Union All

This operation is similar to Union. But it also shows the duplicate rows.
union all in sql

Example of Union All

The First table,
IDNAME
1abhi
2adam
The Second table,
IDNAME
2adam
3Chester
Union All query will be like,
select * from First
UNION ALL
select * from second 
The result table will look like,
IDNAME
1abhi
2adam
2adam
3Chester

Intersect

Intersect operation is used to combine two SELECT statements, but it only retuns the records which are common from both SELECT statements. In case of Intersect the number of columns and datatype must be same. MySQL does not support INTERSECT operator.
intersect in sql

Example of Intersect

The First table,
IDNAME
1abhi
2adam
The Second table,
IDNAME
2adam
3Chester
Intersect query will be,
select * from First
INTERSECT
select * from second 
The result table will look like
IDNAME
2adam

Minus

Minus operation combines result of two Select statements and return only those result which belongs to first set of result. MySQL does not support INTERSECT operator.
minus in sql

Example of Minus

The First table,
IDNAME
1abhi
2adam
The Second table,
IDNAME
2adam
3Chester
Minus query will be,
select * from First
MINUS
select * from second 
The result table will look like,
IDNAME
1abhi

0 Comments:

Post a Comment