Minus in SQL
MINUS in SQL
The MINUS operator is used to return all rows from the first SELECT statement that are not present in the second SELECT statement. It essentially performs a set difference operation between two result sets.
? Syntax:
SELECT column_list FROM table1MINUSSELECT column_list FROM table2;? Example:
Suppose you have two tables:
employees_2023employees_2024
You want to find employees who were in 2023 but not in 2024:
SELECT employee_id FROM employees_2023MINUSSELECT employee_id FROM employees_2024;? Notes:
MINUSis supported in Oracle and some other databases.Equivalent in SQL Server and MySQL is done using:
Using NOT IN:
SELECT employee_id FROM employees_2023WHERE employee_id NOT IN ( SELECT employee_id FROM employees_2024);Using LEFT JOIN and WHERE NULL:
SELECT e1.employee_idFROM employees_2023 e1LEFT JOIN employees_2024 e2 ON e1.employee_id = e2.employee_idWHERE e2.employee_id IS NULL;Let me know if you want examples for a specific SQL dialect or alternatives to MINUS!