SQL Server Except


EXCEPT is available in SQL Server starting with SQL Server 2008. EXCEPT returns distinct rows by comparing the results of two queries. EXCEPT returns distinct rows from the left (first) input query that aren’t output by the right (last) input query. The data and tables are sourced from Philip Burton’s SQL course at Udemy.com. Contrast how EXCEPT works with UNION and INTERSECT.

Consider the following t-SQL code.

1select * from tblDepartment;
2 
3select * -- create a new table
4into tblDepartmentNew
5from tblDepartment  -- has 5 rows
6 
7delete from tblDepartmentNew where Department = 'HR';
8 
9select * from tblDepartment -- has 5 rows
10except
11select * from tblDepartmentNew  -- has 4 rows
12-- we should only see the HR department

Here are the results from SSMS.

So EXCEPT says give me all of the rows in the first table and then delete from that result set all of the matching rows in the second table. What if there was a row in the second table that was not in the fists table? That row simply gets ignored and is not part of the result set.

Duplicates

What if we have duplicates in the first table. We have added some data to the first table. There is a duplicate, namely HR, Bryn. Notice that the results eliminate the duplicate rows from the first table.

1select * from tblDepartment;
2 
3select * -- create a new table
4into tblDepartmentNew
5from tblDepartment  -- has 7 rows with 2 sets of duplicates.
6 
7delete from tblDepartmentNew where Department = 'HR';
8 
9select * from tblDepartmentNew
10 
11select * from tblDepartment -- has 5 rows
12except
13select * from tblDepartmentNew;  -- has 4 rows
14-- we should only see the HR department but the question is
15-- do we get both rows? No we don't.
16 
17with cte as (
18select * from tblDepartment -- has 5 rows
19except
20select * from tblDepartmentNew  -- has 4 rows
21)
22select *
23into tblDepartmentResult
24from cte;

Here are the results from SSMS.