Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MINUS Operator in oracle

MINUS Operator

I have 2 tables A and B.

SELECT COUNT(*) FROM (SELECT * FROM tableA)

returns 389

SELECT COUNT(*) FROM (SELECT * FROM tableB)

returns 217

SELECT COUNT(*) FROM
(SELECT * FROM tableA
INTERSECT
SELECT * FROM tableB)

returns 0

SELECT COUNT(*) FROM 
(SELECT * FROM tableA
MINUS
SELECT * FROM tableB)

returns 389

SELECT COUNT(*) FROM 
(SELECT * FROM tableB
MINUS
SELECT * FROM tableA)

retuns 89

Can someone please explain why does the last query return 89 and not 217?

like image 742
Lizzie Avatar asked Nov 26 '13 05:11

Lizzie


People also ask

Can we use MINUS in Oracle?

You can combine multiple queries using the set operators UNION , UNION ALL , INTERSECT , and MINUS . All set operators have equal precedence. If a SQL statement contains multiple set operators, then Oracle Database evaluates them from the left to right unless parentheses explicitly specify another order.

What is MINUS operator in SQL?

The Minus Operator in SQL is used with two SELECT statements. The MINUS operator is used to subtract the result set obtained by first SELECT query from the result set obtained by second SELECT query.

What is the use of MINUS query?

A Minus Query is a query that uses the MINUS operator in SQL to subtract one result set from another result set to evaluate the result set difference. If there is no difference, there is no remaining result set. If there is a difference, the resulting rows will be displayed.

Is MINUS and except same in SQL?

There is absolutely no difference in the EXCEPT clause and the MINUS clause. They both serve the same purpose and they are simply two different ways of achieving the same functionality. The difference is that EXCEPT is available in the PostgreSQL database while MINUS is available in MySQL and Oracle.


2 Answers

MINUS takes the first result set, and removes any that exist in the second result set; it also removes any duplicates.

In your example, tableA has 389 rows, and tableB has 217 rows; your INTERSECT shows there are no rows in common, which means tableA MINUS tableB is 389 rows (i.e. all of them).

tableB MINUS tableA returns the distinct set of rows in tableB, therefore there are 89 distinct values in tableB.

like image 107
Jeffrey Kemp Avatar answered Oct 07 '22 01:10

Jeffrey Kemp


Suppose if you have set A and B, A = {1,2,3,4} and count(A) = 4, B = {5,6,6,7,7} and count(B) = 5

A-B = {1,2,3,4} thus count(A-B) = count(A) = 4

But B-A = {5,6,7} and count(B) = 3

Thus what we understand here is that minus eliminates the duplicate terms(or rows). That's the reason why the row count reduced from 217 to 89.

Hope this helps.

like image 44
akzhere Avatar answered Oct 06 '22 23:10

akzhere