Intersect in SQL
INTERSECT in SQL
The INTERSECT operator returns only the rows that are common to the results of two SELECT queries. It gives the intersection of two result sets.
Syntax:
SELECT column_list FROM table1INTERSECTSELECT column_list FROM table2;Both
SELECTstatements must return the same number of columns with compatible data types.The result includes distinct rows common to both queries.
Example:
Suppose we have two tables:
Employees_A
| id | name |
|---|---|
| 1 | Alice |
| 2 | Bob |
| 3 | Charlie |
Employees_B
| id | name |
|---|---|
| 2 | Bob |
| 3 | Charlie |
| 4 | David |
Query:
SELECT name FROM Employees_AINTERSECTSELECT name FROM Employees_B;Result:
| name |
|---|
| Bob |
| Charlie |
Notes:
INTERSECTreturns only common rows (distinct).Available in SQL Server, Oracle, PostgreSQL.
Not supported in MySQL (use
INNER JOINorINas alternatives).
If you want, I can show you how to achieve the same result in databases without INTERSECT support!