SQL - Except Operator
In SQL Server, the EXCEPT operator is used to retrieve the distinct rows from the result set of the first SELECT statement that are not present in the result set of the second SELECT statement. It essentially subtracts the rows of one result set from another.
The basic syntax for using the EXCEPT operator in SQL Server is as follows:
SELECT column1, column2, ...
FROM table1
EXCEPT
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 EXCEPT operator compares the result sets of the two SELECT statements and returns a single result set with the distinct rows from the first result set that are not present in the second result set. 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 EXCEPT 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 |
2 |
Jane |
4 |
Tom |
5 |
Sarah |
To retrieve the employees who are not managers (i.e., distinct rows present in "Employees" but not in "Managers"), you can use the EXCEPT operator as follows:
SELECT ID, Name
FROM Employees
EXCEPT
SELECT ID, Name
FROM Managers;
The above query will return the distinct rows from the "Employees" table that are not present in the "Managers" table. Here's the expected output:
As you can see, the result set includes the rows with ID 1 and Name "John", and ID 3 and Name "Mike" because they exist in the "Employees" table but not in the "Managers" table.
It's important to note that the columns, their data types, and their order must match in the SELECT statements for the EXCEPT operator to work correctly.
In summary, the EXCEPT operator in SQL Server allows you to retrieve the distinct rows from the first result set that are not present in the second result set.