SQL | Except Clause
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:
StudentID |
Name |
Course |
1 |
Rohan |
DBMS |
2 |
Kevin |
OS |
3 |
Mansi |
DBMS |
4 |
Mansi |
ADA |
5 |
Rekha |
ADA |
6 |
Megha |
OS |
StudentID |
Name |
Course |
TA Table:
1 |
Kevin |
TOC |
2 |
Sita |
IP |
3 |
Manik |
AP |
4 |
Rekha |
SNS |
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.
Share your thoughts in the comments
Please Login to comment...