SQL - Intersect Operator
In SQL Server, the INTERSECT operator is used to retrieve the common rows between the result sets of two or more SELECT statements. It returns only the distinct rows that are present in all SELECT statements involved in the operation.
The basic syntax for using the INTERSECT operator in SQL Server is as follows:
SELECT column1, column2, ...
FROM table1
INTERSECT
SELECT column1, column2, ...
FROM table2;
In this syntax, column1, column2, etc., represent the columns you want to select from the respective tables (table1, table2, etc.). The SELECT statements can include WHERE, ORDER BY, and other clauses as needed.
The INTERSECT operator combines the result sets of the two SELECT statements and returns a single result set with only the distinct rows that are common to both result sets. The columns in the SELECT statements must have the same data types and be in the same order.
Here's an example to illustrate the usage of the INTERSECT operator:
Consider two tables, "Employees" and "Managers", with the following structures:
Table: Employees
ID |
Name |
1 |
John |
2 |
Jane |
3 |
Mike |
Table: Managers
ID |
Name |
1 |
Jane |
2 |
Tom |
3 |
Sarah |
To retrieve the employees who are also managers (i.e., common rows), you can use the INTERSECT operator as follows:
SELECT ID, Name
FROM Employees
INTERSECT
SELECT ID, Name
FROM Managers;
The above query will return the distinct rows that are present in both the "Employees" and "Managers" tables. Here's the expected output:
As you can see, the result set includes only the row with ID 2 and Name "Jane" because it is the only row that exists in both tables.
It's important to note that the columns, their data types, and their order must match in the SELECT statements for the INTERSECT operator to work correctly.
In summary, the INTERSECT operator in SQL Server allows you to retrieve the distinct common rows between the result sets of two or more SELECT statements.