SQL - MINUS Keyword
The SQL MINUS keyword is used to compare the result-sets of two or more SQL SELECT statements. It returns all records from the first result-set that do not appear in the second result-set.
While using MINUS keyword, the following criteria must be satisfied:
- Number of columns in each SELECT statement should equal.
- Datatype of columns in each SELECT statement should match.
- Order of columns in each SELECT statement should match.
Syntax
The syntax for using MINUS keyword is given below:
SELECT column1, column2, ... FROM table1 MINUS [ALL] SELECT column1, column2, ... FROM table2
Example:
Consider database tables called Product and Inventory with the following records:
Table 1: Product table
Name | Brand | Price | Quantity |
---|---|---|---|
Apple | Delicious | 1.5 | 40 |
Apple | Harvest | 1.6 | 50 |
Orange | Delicious | 2.0 | 40 |
Orange | Harvest | 1.9 | 50 |
Watermelon | LocalFarm | 4.0 | 50 |
Mango | LocalFarm | 3.5 | 60 |
Table 2: Inventory table
Name | Brand | Price | Quantity |
---|---|---|---|
Apple | Delicious | 1.5 | 20 |
Orange | LocalFarm | 2.0 | 40 |
Watermelon | LocalFarm | 4.0 | 20 |
-
Using MINUS keyword: To get the records of Name column which are not present in both record-sets, the following SQL code can be used:
SELECT Name FROM Product MINUS SELECT Name FROM Inventory ORDER BY Name;
This will produce the result as shown below:
Name Mango -
Using MINUS keyword with WHERE clause: To fetch the records of Name column which are not present in both record-sets with the specified condition, the following SQL code can be used:
SELECT Name FROM Product MINUS SELECT Name FROM Inventory WHERE Quantity < 30 ORDER BY Name;
This will produce the following result:
Name Mango Orange -
Using MINUS keyword with multiple columns: To fetch the records of Name and Brand columns which are not present in both record-sets, the following SQL code can be used:
SELECT Name, Brand FROM Product MINUS SELECT Name, Brand FROM Inventory ORDER BY Name;
This will produce the following result:
Name Brand Apple Harvest Mango LocalFarm Orange Delicious Orange Harvest
❮ SQL Keywords