Interview Question of the Week #043 – What is the Difference Between EXCEPT operator vs. NOT IN

Question: What is the Difference Between EXCEPT operator vs. NOT IN

Interview Question of the Week #043 - What is the Difference Between EXCEPT operator vs. NOT IN ExceptOperator-800x388

Answer: The EXCEPT operator returns all of the distinct rows from the query to the left of the EXCEPT operator when there are no matching rows in the right query. The EXCEPT operator is equivalent of the Left Anti Semi Join. EXCEPT operator works the same way NOT IN. EXCEPTS returns any distinct values from the query to the left of the EXCEPT operand that does not also return from the right query.

An example of EXCEPT operator is displayed along with an example of NOT IN. If you run both of the Query and compare the Execution plan it is exactly the same. EXCEPT and NOT IN does the same functions and have the same execution plan, but EXCEPT has a much simpler syntax. The row-by-row comparison provided by EXCEPT, combined with the number of rows being returned remaining consistent, provides compelling evidence that the re-factored query is correct. EXCEPT works with * as well as aliases.

Example: (Both of the scripts returns the same number of rows)

-- SQL SERVER 2005 Method
USE AdventureWorks;
GO
SELECT ProductID
FROM Production.Product
EXCEPT
SELECT ProductID
FROM Production.WorkOrder; 
GO
-- SQL SERVER 2000 Method which works IN SQL SERVER 2005
USE AdventureWorks;
GO
SELECT ProductID
FROM Production.Product
WHERE ProductID
NOT IN (
SELECT ProductID
FROM Production.WorkOrder);
GO

Interview Question of the Week #043 - What is the Difference Between EXCEPT operator vs. NOT IN SQLSERVER_EXCEPT_ExecPlan_small-1

If you liked this video, please do not forget to subscribe to my YouTube Channel – SQL in Sixty Seconds.

Here are my few recent videos and I would like to know what is your feedback about them.

Reference: Pinal Dave (https://blog.sqlauthority.com)

SQL Joins, SQL Scripts, SQL Server
Previous Post
Interview Question of the Week #042 – How Does SPACE Function Works in SQL Server?
Next Post
Interview Question of the Week #044 – What is the difference of performance between SELECT and SET?

Related Posts

Leave a Reply