Skip to content
Related Articles

Related Articles

SQL | Except Clause
  • Difficulty Level : Easy
  • Last Updated : 06 Sep, 2018

In SQL, EXCEPT returns those tuples that are returned by the first SELECT operation, and not returned by the second SELECT operation.

This is the same as using a subtract operator in relational algebra.

Example:
Say we have two relations, Students and TA (Teaching Assistant). We want to return all those students who are not teaching assistants. The query can be formulated as:

Students Table:

StudentIDNameCourse
1RohanDBMS
2KevinOS
3MansiDBMS
4MansiADA
5RekhaADA
6MeghaOS
StudentIDNameCourse

TA Table:



1KevinTOC
2SitaIP
3ManikAP
4RekhaSNS
SELECT Name
       FROM Students
EXCEPT
SELECT NAME
       FROM TA;

Output:

Rohan
Mansi
Megha

To retain duplicates, we must explicitly write EXCEPTALL instead of EXCEPT.

SELECT Name
       FROM Students
EXCEPTALL
SELECT Name
       FROM TA;

Output:

Rohan
Mansi
Mansi
Megha

Difference between EXCEPT and NOT IN Clause
EXCEPT automatically removes all duplicates in the final result, whereas NOT IN retains duplicate tuples. It is also important to note that EXCEPT is not supported by MySQL.

This article is contributed by Anannya Uberoi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :