MINUS Operator in ORACLE

When I was working in the office I wanted to get some data from Oracle database. Yeah yeah If I say simple way, I wanted to write a query to get data. This is the situation,

Let’s say I have a Table A and Table B and I want to get Data exist in Table A and not in Table B (blue colour area)

download

First I had no idea how to do that and I searched it and found this keyword MINUS

Syntax:

SELECT expression1, expression2, ... expression_n
FROM tables
[WHERE conditions]
MINUS
SELECT expression1, expression2, ... expression_n
FROM tables
[WHERE conditions];

Note : Both SELECT statement must have same number of fields in the result set with similar data types.

Example:

SELECT A_id
FROM TABLE_A
MINUS
SELECT B_id
FROM TABLE_B;

This Oracle MINUS example returns all A_id values that are in the TABLE_A  table and not in the TABLE_B table. What this means is that if a A_id value existed in the TABLE_A table and also existed in the TABLE_B table, the A_id value would not appear in this result set.
MINUS takes the first result set, and removes any that exist in the second result set; it also removes any duplicates.

Suppose A = {1,2,3,4}
B = {4,5,6,6,7}
A-B (A minus B) = {1,2,3}
B-A = {5,6,7}

I Think now you can understand what is the use of MINUS keyword. Try your own examples.

Thank you. 🙂

Leave a comment