The SQL EXCEPT operator joins two SELECT statements and retrieves rows from the first SELECT statement not obtained by the second SELECT statement. This indicates that EXCEPT only returns entries that aren’t accessible in the second SELECT query.
SELECT <Attributes> FROM <Table1>
EXCEPT
SELECT <Attributes> FROM <Table2>
The following illustration helps us to grab this concept more firmly. Let’s look into it.
To determine which students are not participating in cricket, utilize the EXCEPT statement.
use msdb;
-- Create Student table
CREATE TABLE dbo.Students
(
ID int,
Name varchar(15),
Age int
);
-- Insert values
INSERT INTO dbo.Students VALUES(1, "Hamid", 21);
INSERT INTO dbo.Students VALUES(2, "Haris", 24);
INSERT INTO dbo.Students VALUES(3, "Ali", 22);
INSERT INTO dbo.Students VALUES(4, "Jawad", 21);
INSERT INTO dbo.Students VALUES(5, "Khan", 25);
INSERT INTO dbo.Students VALUES(6, "Moiz", 20);
-- Display Students table
SELECT * FROM msdb.dbo.Students
-- Create Cricker_Team table
CREATE TABLE dbo.Cricket_Team
(
Player varchar(15),
Role varchar(15)
);
-- Insert values
INSERT INTO dbo.Cricket_Team VALUES("Hamid", "Batsman");
INSERT INTO dbo.Cricket_Team VALUES("Haris", "Keeper");
INSERT INTO dbo.Cricket_Team VALUES("Moiz", "Batsman");
-- Dislay Cricker_Team table
SELECT * FROM msdb.dbo.Cricket_Team
-- Using except statement
SELECT Name FROM dbo.Students
Except
SELECT Player FROM dbo.Cricket_Team;
-- Dropping tables
drop table msdb.dbo.Students;
drop table msdb.dbo.Cricket_Team;
msdb.Students table using schema dbo.Students table.Students table.Cricket_Team table using schema dbo.Cricket_Team table.EXCEPT keyword to find out which students are not taking part in cricket.DROP statement to delete the Students and Cricket_Team tables.Free Resources