This Oracle tutorial explains how to use the Oracle MINUS operator with syntax and examples.
The Oracle MINUS operator is used to return all rows in the first SELECT statement that are not returned by the second SELECT statement. Each SELECT statement will define a dataset. The MINUS operator will retrieve all records from the first dataset and then remove from the results all records from the second dataset.
Explanation: The MINUS query will return the records in the blue shaded area. These are the records that exist in Dataset1 and not in Dataset2.
Each SELECT statement within the MINUS query must have the same number of fields in the result sets with similar data types.
The syntax for the MINUS operator in Oracle/PLSQL is:
The columns or calculations that you wish to retrieve.
The tables that you wish to retrieve records from. There must be at least one table listed in the FROM clause.
Optional. The conditions that must be met for the records to be selected.
The following is an Oracle MINUS operator example that returns one field with the same data type:
This Oracle MINUS example returns all supplier_id values that are in the suppliers table and not in the orders table. What this means is that if a supplier_id value existed in the suppliers table and also existed in the orders table, the supplier_id value would not appear in this result set.
The following is a MINUS operator example that uses an ORDER BY clause:
In this MINUS example, since the column names are different between the two SELECT statements, it is more advantageous to reference the columns in the ORDER BY clause by their position in the result set. In this example, we've sorted the results by supplier_name / company_name in ascending order, as denoted by the ORDER BY 2.
The supplier_name / company_name fields are in position #2 in the result set.