Reputation: 25
In this example, I'm trying to return a list of values (in this case, company names) that have no entries in another table (entries in this case meaning invoices). In other words, I'm trying to return a list of companies that have no invoices. Here is my code:
Select CompanyName
From tblCompany join tblInvoice
ON tblCompany.CompanyID = tblInvoice.CompanyID
Where tblCompany.CompanyID NOT IN
(Select CompanyID
From tblInvoice)
What I'm trying to get is this:
However, when I run the code, no values show up. Can anyone tell me why?
Upvotes: 1
Views: 46
Reputation: 11
Use the below query for desired results.
Select CompanyName
From tblCompany
left join tblInvoice
ON tblCompany.CompanyID = tblInvoice.CompanyID
Where tblInvoice.CompanyID IS NULL
Upvotes: 0
Reputation: 6719
Try this
Select CompanyName
From tblCompany
Where tblCompany.CompanyID NOT IN
( Select CompanyID
From tblInvoice)
That is get all the CompanyName
from tblCompany
where the CompanyID
not exists in the tblInvoice
.
Or you can try the below one,
select CompanyName
from tblCompany
left join tblInvoice on tblCompany.CompanyID = tblInvoice.CompanyID
where tblInvoice.CompanyID is null
Upvotes: 1
Reputation: 425003
Use left join and filter on nulls:
select CompanyName
from tblCompany
left join tblInvoice on tblCompany.CompanyID = tblInvoice.CompanyID
where tblInvoice.CompanyID is null
This works because missed joins return nulls in the joined table's values.
Upvotes: 1