Tuesday, March 24, 2015

Using SQL Minus to compare the difference of two tables

THE SQL MINUS OPERATOR IS USED TO RETURN ALL ROWS IN THE FIRST SELECT STATEMENT THAT ARE NOT RETURNED IN THE SECOND SELECT STATEMENT.

Each SELECT statement within the MINUS query must have the same number of fields in the result sets with similar data types.

SYNTAX

The syntax for the SQL MINUS operator is:
SELECT expression1, expression2, ... expression_n
FROM tables
MINUS
SELECT expression1, expression2, ... expression_n
FROM tables;

EXAMPLE - WITH SINGLE EXPRESSION

The following is a SQL MINUS operator example that has one field with the same data type:
SELECT supplier_id
FROM suppliers
MINUS
SELECT supplier_id
FROM orders;
This SQL 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.

EXAMPLE - USING ORDER BY CLAUSE

The following is a MINUS operator example that uses the ORDER BY clause:
SELECT supplier_id, supplier_name
FROM suppliers
WHERE supplier_id > 2000
MINUS
SELECT company_id, company_name
FROM companies
WHERE company_id > 1000
ORDER BY 2;
In this SQL MINUS operator 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.

No comments:

Post a Comment