SET+Operators
SET+Operators
SQL
BY
JANARDHANA BANDI
SET OPERATORS
SET OPERATORS IN SQL
• Set Operators in SQL are same as Set Operators in Mathematics.
• Used to combine or compare two or more datasets.
• Below are the rules to perform Set operations
• Number of columns must be same in all Select queries
• Order of columns must be same in all Select queries
• Datatypes must be compatible
Below are the 4 set operators is SQL:
1. UNION
2. UNION ALL
3. INTERSECT
4. MINUS
UNION
UNION: Union is used to combine result sets of two or more Select queries.
After combining the result sets it eliminate duplicates if any, that means if
same record exists in both result sets it shows only one record in the
TABLE_B
output. TABLE_A
empid name
empid name
Syntax: 22 Gopal
21 Raja
SELECT col1, col2, …col_n FROM TABLE_A 25 Seetha
22 Gopal 28 Kamal
UNION
SELECT col1, col2, …col_n FROM TABLE_B TABLE_A UNION
TABLE_B
UNION empid name
SELECT col1, col2, …col_n FROM TABLE_C 21 Raja
22 Gopal
…..
25 Seetha
28 Kamal
UNION ALL
UNION ALL: Same as Union but Union all but it doesn’t eliminate
duplicates.
TABLE_B
TABLE_A
Syntax: empid name
empid name
SELECT col1, col2, …col_n FROM TABLE_A 22 Gopal
21 Raja
25 Seetha
UNION ALL 22 Gopal 28 Kamal
SELECT col1, col2, …col_n FROM TABLE_B
TABLE_A UNION ALL
UNION ALL TABLE_B
SELECT col1, col2, …col_n FROM TABLE_C empid name
….. 21 Raja
22 Gopal
22 Gopal
25 Seetha
28 Kamal
INTERSECT
INTERSECT: It returns only common rows between both the tables.
Syntax:
SELECT col1, col2, …col_n FROM TABLE_A TABLE_B
TABLE_A
INTERSECT empid name
empid name
22 Gopal
SELECT col1, col2, …col_n FROM TABLE_B 21 Raja
25 Seetha
INTERSECT 22 Gopal 28 Kamal
SELECT col1, col2, …col_n FROM TABLE_C
….. TABLE_A INTERSECT
TABLE_B
empid name
22 Gopal
MINUS
MINUS: It returns the records that exists in first result set and do not exists
in the next result set. Very useful for data validation between two tables.
TABLE_B
TABLE_A
Syntax: empid name
empid name
22 Gopal
SELECT col1, col2, …col_n FROM TABLE_A 21 Raja
25 Seetha
MINUS 22 Gopal 28 Kamal
SELECT col1, col2, …col_n FROM TABLE_B
Janardhana
Bandi