Except In SQL

Galaxy Glossary

How do you find the rows in one result set that are not present in another?

The EXCEPT operator in SQL is used to return all rows from the first SELECT statement that are not present in the second SELECT statement. It's a powerful tool for set-based comparisons, useful for identifying differences between data sets.
Sign up for the latest in SQL knowledge from the Galaxy Team!
Thank you! Your submission has been received!
Oops! Something went wrong while submitting the form.

Description

The EXCEPT operator, sometimes called MINUS, is a set operator in SQL. It's used to compare two result sets and return only the rows that are present in the first result set but not in the second. Think of it like finding the difference between two lists. This is particularly useful for identifying discrepancies in data or for comparing data from different sources. For example, you might use EXCEPT to find customers in one database who aren't in another, or to identify products listed in one catalog but not another. The key is that both result sets must have the same structure (column names and data types). The order of the result set is not guaranteed and is dependent on the underlying database implementation. Using EXCEPT is more efficient than using a subquery for this type of comparison, especially with large datasets. It's a concise and elegant way to perform set operations in SQL.

Why Except In SQL is important

The EXCEPT operator is crucial for data analysis and comparison tasks. It allows developers to quickly identify differences between datasets, which is essential for data integrity checks, reporting, and troubleshooting.

Example Usage


-- Create two sample tables
CREATE TABLE Customers (
    CustomerID INT,
    FirstName VARCHAR(50)
);

CREATE TABLE ActiveCustomers (
    CustomerID INT,
    FirstName VARCHAR(50)
);

-- Insert some data
INSERT INTO Customers (CustomerID, FirstName) VALUES
(1, 'Alice'),
(2, 'Bob'),
(3, 'Charlie');

INSERT INTO ActiveCustomers (CustomerID, FirstName) VALUES
(1, 'Alice'),
(2, 'Bob');

-- Use EXCEPT to find customers in Customers but not in ActiveCustomers
SELECT CustomerID, FirstName
FROM Customers
EXCEPT
SELECT CustomerID, FirstName
FROM ActiveCustomers;

Common Mistakes

Want to learn about other SQL terms?