EXCEPT
EXCEPT

EXCEPT

Status
Done

(show you how to use the EXCEPT operator to find the set difference between two sets of data.)

image
💡
Note that the EXCEPT operator is supported in MySQL starting from version 8.0.31. If you use a lower version, you can emulate the EXCEPT (or MINUS) operator.

Introduction

In MySQL, the EXCEPT operator acts like a data filter, helping you find rows present in one query's result set but missing from another's. Here's a breakdown of its basic syntax in plain language:

EXCEPT in Action:

Imagine you have two lists:

  • List 1: Contains all the students enrolled in your class.
  • List 2: Contains students who have completed their assignments.

You want to find students who are enrolled (List 1) but haven't submitted assignments yet (not in List 2). EXCEPT helps you achieve this.

Basic EXCEPT Syntax:

SQL

SELECT ... FROM table1
EXCEPT
SELECT ... FROM table2;
  • SELECT ...: This represents the individual SELECT statements that retrieve data.
  • FROM table1, table2: These are the tables from which data is fetched.
  • EXCEPT: This keyword is the core of the operation. It compares the results of the two SELECT statements.

Key Points:

  • Finding Differences: EXCEPT returns rows from table1 that are not present in table2 based on a comparison of all columns involved (similar to a set difference).
  • Matching Columns (Implicit): By default, EXCEPT assumes the columns in both SELECT statements have the same number, order, and compatible data types.
  • Duplicate Removal (Default): EXCEPT eliminates duplicate rows in the final result set by default (similar to UNION DISTINCT).
  • Keeping Duplicates (Optional): If you want to include all rows, including duplicates, use EXCEPT ALL instead of just EXCEPT.
  • The EXCEPT operator returns a query set with column names derived from the column names of the first query (query1).

Simple MySQL EXCEPT operator example

Practical MySQL EXCEPT operator example

Using the EXCEPT operator with the ORDER BY clause example

Using the EXCEPT operator with the ALL option

Summary

  • Use the MySQL EXCEPT operator to retrieve rows from one result set that do not appear in another result set.
  • EXCEPT DISTINCT removes duplicates while the EXCEPT ALL retains the duplicates.
  • The EXCEPT operator uses the DISTINCT option by default.