SQL INTERSECT Operator
INTERSECT operator allows you to combine two table expressions into one and return a result set which consists of rows that appear in the results of both table expressions. INTERSECT operator, like UNION operator, removes all duplicated row from the result sets. Unlike the UNION operator, INTERSECT operator operates as AND operator on tables expression. It means data row appears in both table expression will be combined in the result set while UNION operator operates as OR operator (data row appear in one table expression or both will be combined into the result set). The syntax of using INTERSECT operator is like UNION as follows:
table_expression1 INTERSECT table_expression2
Table expression can be any select statement which has to be union compatible and ORDER BY can be specified only behind the last table expression.
Be note that several RDBMS, including MySQL (version < 5.x), does not support INTERSECT operator.
This is an example of using INTERSECT operator. Here is the employees sample table
employee_id name department_id job_id salary
----------- -------- ------------- ------ -------
1 jack 1 1 3000.00
2 mary 2 2 2500.00
3 newcomer (NULL) 0 2000.00
4 anna 1 1 2800.00
5 Tom 2 2 2700.00
6 foo 3 3 4700.00
We can find employee who work in department id 1 and two and have salary greater than 2500$ by using INTERSECT operator. This example using the sample table in both table expressions, you can test it on two different tables.)
SELECT * FROM employees WHERE department_id in (1,2) INTERSECT SELECT * FROM employees WHERE salary > 2500
employee_id name department_id job_id salary
----------- ------ ------------- ------ -------
1 jack 1 1 3000.00
4 anna 1 1 2800.00
5 Tom 2 2 2700.00