Disclaimer: I have figured out the problem (I think), but I wanted to add this issue to Stack Overflow since I couldn\'t (easily) find it anywhere. Also, someone might
this worked for me :)
select * from Common
where
common_id not in (select ISNULL(common_id,'dummy-data') from Table1)
and common_id not in (select ISNULL(common_id,'dummy-data') from Table2)
select *
from Common c
where not exists (select t1.commonid from table1 t1 where t1.commonid = c.commonid)
and not exists (select t2.commonid from table2 t2 where t2.commonid = c.commonid)
select *,
(select COUNT(ID) from ProductMaster where ProductMaster.CatID = CategoryMaster.ID) as coun
from CategoryMaster
Please follow the below example to understand the above topic:
Also you can visit the following link to know Anti join
select department_name,department_id from hr.departments dep
where not exists
(select 1 from hr.employees emp
where emp.department_id=dep.department_id
)
order by dep.department_name;
DEPARTMENT_NAME DEPARTMENT_ID
Benefits 160
Construction 180
Contracting 190
.......
But if we use NOT IN
in that case we do not get any data.
select Department_name,department_id from hr.departments dep
where department_id not in (select department_id from hr.employees );
no data found
This is happening as (select department_id from hr.employees
) is returning a null value and the entire query is evaluated as false. We can see it if we change the SQL slightly like below and handle null values with NVL function.
select Department_name,department_id from hr.departments dep
where department_id not in (select NVL(department_id,0) from hr.employees )
Now we are getting data:
DEPARTMENT_NAME DEPARTMENT_ID
Treasury 120
Corporate Tax 130
Control And Credit 140
Shareholder Services 150
Benefits 160
....
Again we are getting data as we have handled the null value with NVL function.
I had an example where I was looking up and because one table held the value as a double, the other as a string, they would not match (or not match without a cast). But only NOT IN. As SELECT ... IN ... worked. Weird, but thought I would share in case anyone else encounters this simple fix.
Table1 or Table2 has some null values for common_id. Use this query instead:
select *
from Common
where common_id not in (select common_id from Table1 where common_id is not null)
and common_id not in (select common_id from Table2 where common_id is not null)