- SQL Basics
- SQL Introduction
- SQL Syntax
- SQL Sample Database
- SQL SELECT
- SQL WHERE
- SQL ORDER BY
- SQL DISTINCT
- SQL LIMIT
- SQL FETCH
- SQL AND
- SQL OR
- SQL BETWEEN
- SQL IN
- SQL LIKE
- SQL IS NULL
- SQL Comparison Operators
- SQL Logical Operators
- SQL Alias
- SQL CASE
- Joins and Subqueries
- SQL INNER JOIN
- SQL LEFT JOIN
- SQL RIGHT JOIN
- SQL FULL OUTER JOIN
- SQL SELF JOIN
- SQL CROSS JOIN
- SQL Subquery
- SQL Correlated Subquery
- SQL UNION
- SQL INTERSECT
- SQL EXCEPT
- Aggregate Functions
- SQL AVG
- SQL COUNT
- SQL MAX
- SQL MIN
- SQL SUM
- SQL GROUP BY
- SQL HAVING
- SQL ROLLUP
- SQL CUBE
- SQL GROUPING SETS
- Database Management
- SQL CREATE DATABASE
- SQL ALTER DATABASE
- SQL DROP DATABASE
- SQL BACKUP DATABASE
- SQL SHOW DATABASES
- SQL SELECT DATABASE
- Table Management
- SQL CREATE TABLE
- SQL ALTER TABLE
- SQL ADD COLUMN
- SQL DROP COLUMN
- SQL DROP TABLE
- SQL TRUNCATE TABLE
- SQL SHOW TABLES
- SQL RENAME TABLE
- SQL Constraints
- SQL Primary Key
- SQL Foreign Key
- SQL UNIQUE Constraint
- SQL CHECK Constraint
- SQL NOT NULL Constraint
SQL EXCEPT
The EXCEPT operator in SQL acts like a mathematical subtraction for your data. It allows you to retrieve all unique rows from the first SELECT statement that do not appear in the results of the second SELECT statement. Think of it as finding the "difference" between two datasets.
While operators like UNION combine results and INTERSECT finds common ground, EXCEPT is specifically designed to filter out matches, leaving you only with the records unique to your primary query.
EXCEPT operator is called MINUS. They perform the exact same function, but the keyword varies by SQL dialect.
Syntax of SQL EXCEPT
SELECT column1, column2, ...
FROM table1
WHERE condition
EXCEPT
SELECT column1, column2, ...
FROM table2
WHERE condition;
- SELECT statements: These are your standard queries. The first query acts as your base set, and the second query acts as the filter.
- EXCEPT: This operator tells the database to take the results of the first query and remove any rows that also appear in the second query.
- Columns: For the operation to work, both queries must return the same number of columns, and those columns must have compatible data types in the same order.
SELECT *. This ensures that your queries remain compatible even if table schemas change in the future.
Key Points
- Exclusion Logic: The
EXCEPToperator returns rows from the first query that are not present in the second query. - Automatic Deduplication: By default,
EXCEPTreturns only unique rows. If the first query has duplicate rows that aren't in the second query, only one instance of that row will appear in the final result. - Data Alignment: The number of columns and the data types must match exactly between the two
SELECTqueries, or the database will throw an error. - Order Matters: Unlike
UNIONorINTERSECT, the order of queries in anEXCEPTstatement is critical.Query A EXCEPT Query Bis very different fromQuery B EXCEPT Query A.
EXCEPT compares the entire row. If you select three columns in the first query and those same three columns don't match perfectly in the second, the row will not be excluded.
Example of SQL EXCEPT
Imagine you are managing two lists of employees: one for a specific project team (Department A) and one for a general company newsletter (Department B). You want to find out which team members are only on the project team and not on the general list.
Table 1: Employees (Department A)
Table 2: Employees (Department B)
Using the EXCEPT operator, we can isolate the employees who exist in Department A but are missing from Department B:
SELECT name, department
FROM employees_1
EXCEPT
SELECT name, department
FROM employees_2;
Output:
Explanation:
- The database looks at the first list (John, Alice, Bob).
- It then looks at the second list (Alice, Bob, Sarah).
- Alice and Bob are found in both, so they are removed from the result.
- John is unique to the first list, so he remains.
- Note that "Sarah" is ignored because she was only in the second list, and
EXCEPTonly cares about what is "missing" from the first list.
SQL EXCEPT with Conditions
In many real-world scenarios, you only want to compare a subset of data. You can apply WHERE clauses to either or both queries to narrow down your results. For example, if you only wanted to compare employees within the 'HR' department specifically:
SELECT name, department
FROM employees_1
WHERE department = 'HR'
EXCEPT
SELECT name, department
FROM employees_2
WHERE department = 'HR';
Output:
This is extremely useful for tasks like identifying "customers who bought Product A but never bought Product B" or "users who signed up last month but haven't logged in this month."
Summary
The EXCEPT operator is an essential tool for data analysis and cleanup. It allows you to quickly identify discrepancies between two datasets by returning only the unique rows from the first query that are absent in the second. By keeping column counts and data types aligned, you can use EXCEPT to perform complex data subtractions with minimal code.