Showing posts with label UNION. Show all posts
Showing posts with label UNION. Show all posts

Tuesday, October 11, 2016

DIFFERENCE AMONG UNION, MINUS AND INTERSECT? : SQL UNION VS MINUS VS INTERSECT DIFFERENCE

WHAT IS THE DIFFERENCE AMONG UNION, MINUS AND INTERSECT?
UNION combines the results from 2 tables and eliminates duplicate records from the result set.
MINUS operator when used between 2 tables, gives us all the rows from the first table except the rows which are present in the second table.
INTERSECT operator returns us only the matching or common rows between 2 result sets.
To understand these operators, let’s see some examples. We will use two different queries to extract data from our emp table and then we will perform UNION, MINUS and INTERSECT operations on these two sets of data.
UNION
SELECT * FROM EMPLOYEE WHERE ID = 5
UNION
SELECT * FROM EMPLOYEE WHERE ID = 6
ID
MGR_ID
DEPT_ID
NAME
SAL
DOJ
5
2
2.0
Anno
80.0
01-Feb-2012
6
2
2.0
Darl
80.0
11-Feb-2012
MINUS
SELECT * FROM EMPLOYEE
MINUS
SELECT * FROM EMPLOYEE WHERE ID > 2
ID
MGR_ID
DEPT_ID
NAME
SAL
DOJ
1
2
Hash
100.0
01-Jan-2012
2
1
2
Robo
100.0
01-Jan-2012
INTERSECT
SELECT * FROM EMPLOYEE WHERE ID IN (2, 3, 5)
INTERSECT
SELECT * FROM EMPLOYEE WHERE ID IN (1, 2, 4, 5)

ID
MGR_ID
DEPT_ID
NAME
SAL
DOJ
5
2
2
Anno
80.0
01-Feb-2012
2
1
2
Robo
100.0
01-Jan-2012

WHAT IS THE DIFFERENCE BETWEEN JOIN AND UNION

WHAT IS THE DIFFERENCE BETWEEN JOIN AND UNION?
SQL JOIN allows us to “lookup” records on other table based on the given conditions between two tables. For example, if we have the department ID of each employee, then we can use this department ID of the employee table to join with the department ID of department table to lookup department names.
UNION operation allows us to add 2 similar data sets to create resulting data set that contains all the data from the source data sets. Union does not require any condition for joining. For example, if you have 2 employee tables with same structure, you can UNION them to create one result set that will contain all the employees from both of the tables.

SELECT * FROM EMP1
UNION
SELECT * FROM EMP2;