Professional Documents
Culture Documents
UNION ALL, MINUS, and INTERSECT. The INTERSECT operator returns the distinct
(common) elements in two sets or common records from two or more tables. In
other words, it compares the result obtained by two queries and produces unique
rows, which are the result returned by both queries.
Syntax
The following are the syntax that illustrates the use of the INTERSECT operator:
Let us first creates two tables with the following structure to understand the
INTERSECT operator:
o The number and order of the columns should be the same in all tables that you are
going to use.
o The data type must be compatible with the corresponding positions of each select
query.
o The column name selected in the different SELECT queries must be in the same order.
We can understand the Union operator with the following visual representation:
In the above image, we can see that the Union operator removes the duplicate rows
and returns unique rows only.
MySQL MINUS
The MINUS operator is a kind of SET operation in SQL which also includes
INTERSECT, UNION, and UNION ALL. The MINUS operator returns the unique
element from the first table/set, which is not found in the second table/set. In
other words, it will compare the results of two queries and produces the resultant
row from the result set obtained by the first query and not found in the result set
obtained by the second query.
Syntax
The following are the syntax that illustrates the use of a MINUS operator:
The following are the rules for a statement that uses the MINUS operator:
o The number and order of columns in all the SELECT statements must be the same.
o The data types of the corresponding columns in both SELECT statements must be the
same or convertible.
We can understand the MINUS operator with the following visual representation.
Here this operator returns the distinct/unique values from the result obtained by
the first SELECT statement and not found in the result obtained by the second
SELECT statement:
Simulation of MySQL MINUS Operator
Since MySQL does not provide support for MINUS operator. However, we can use
a LEFT JOIN clause to simulate this operator.
Example
Let us first creates two tables with the following structure for the demonstration:
Output:
After executing the above query, we should get the output as below image: