Set Operaters: Definition
Set Operaters: Definition
Definition:
SQL set operators allows combine results from two or more SELECT statements or Set operators combine sets of rows returned by queries, instead of individual data items .
TYPES:
- UNION - UNION ALL - INTERSECT - MINUS
You can combine multiple queries using the set operators UNION, UNION ALL, INTERSECT, and MINUS.
UNION:
The UNION operator is used to combine the result-set of two or more SELECT statements. Display data from both queries , eliminating duplicate rows. By default order is ascending.
SYNTAX:
EXAMPLE:
SELECT A FROM T1;
A 1 2 3 4
B 1 2 3 5
RESULT:
A 1 2 3 4 5
UNION ALL:
Display data from both queries including duplicate rows By default order is descending.
SYNTAX:
select field1, field2, ... field_n from tables UNION ALL select field1, field2, ... field_n from tables;
EXAMPLE:
SELECT A FROM T1;
A 1 2 3 4
B 1 2 3 5
RESULT:
A 1 2 3 4 1 2 3 5
INTERSECT:
INTERSECT returns only common rows returned by the two SELECT statements. MySQL does not support INTERSECT operator.
SYNTAX:
select field1, field2, . field_n from tables INTERSECT select field1, field2, . field_n from tables;
EXAMPLES:
A 1 2 3 4
B 1 2 3 5
RESULT:
A 1 2
MINUS:
The SQL MINUS query returns all rows in the first SQL SELECT statement that are not returned in the second SQL SELECT statement.
SYNTAX:
select field1, field2, ... field_n from tables MINUS select field1, field2, ... field_n from tables;
EXAMPLE:
A 1 2 3 4
B 1 2 3 5
RESULT:
A 4
INTERVIEW QUESTIONS:
1.
SELECT 1 FROM DUAL UNION SELECT 2 FROM DUAL UNION ALL SELECT 2 FROM DUAL INTERSECT SELECT 2 FROM DUAL MINUS SELECT 1 FROM DUAL; }2 }2 }1,2,2 } 1,2
RESULT:
1 2
2.
SELECT 2 FROM DUAL UNION SELECT 1 FROM DUAL;
RESULT:
2 1 2
First row column(2) only occur in the title, the union default order is ascending, so it prints the value In ascending.
ERRORS:
Example:
SELECT 1 FROM DUAL UNION SELECT A FROM DUAL This error will Display like this:
ORA-01790: expression must have same data type as corresponding expression.
4.
When you give 2 column in one row and 1 column in another row then The error will occur.
EXAMPLE:
SELECT 1,2 FROM DUAL UNION SELECT 1 FROM DUAL
SELECT A FROM T1 MINUS SELECT B FROM T1 UNION (SELECT B FROM T2 MINUS SELECT A FROM T1); }5 }4,5 }4
RESULT:
B 4 5
-------------------------------------XXXX---------------------------------------