Manushree Mishra
Manushree Mishra

Reputation: 87

SQL MINUS operator

select deptno  
from emp2  
MINUS  
select deptno 
from dpt  
order by deptno;  

the above query returns = No Data Found

Whereas,

select deptno,ename   
from emp2  
MINUS  
select deptno,dname 
from dpt   
order by deptno;  

returns all the deptno and ename field values.

Can you explain why am I getting all the values of deptno field despite using MINUS operator in the second query?

legend: 
emp is employee table and dpt is department table,
ename is employee name -belonging to emp,
dname is department name -belonging to dpt,
deptno is department no. -common to both

Upvotes: 2

Views: 899

Answers (1)

Lukasz Szozda
Lukasz Szozda

Reputation: 175616

In the first query there is no different deptno between tables, in the second you have the same deptno, but the names are different

Think about it like this:

Query 1:

select deptno  
from emp2  
MINUS  
select deptno 
from dpt  
order by deptno; 

Example:

[1,2,3,4] - [1,2,3,4] = empty

Query 2:

select deptno,ename   
from emp2  
MINUS  
select dept no,dname 
from dpt  
order by deptno; 

Example:

[(1, 'a'),(2, 'b'),(3, 'c'),(4, 'd')] - 
[(1, 'z'),(2, 'x'),(3, 'u'),(4, 'w')] = 
[(1, 'a'),(2, 'b'),(3, 'c'),(4, 'd')]

MINUS

MINUS operator, which returns only unique rows returned by the first query but not by the second

Upvotes: 6

Related Questions