Reputation: 53
I am trying to list the Company Name of all U.S.-based customers who are NOT located in the same state (or region) as any of the employees. It should return 10 rows. I have used the following query for this
SELECT Customers.CompanyName
FROM Customers
WHERE Customers.Country='USA'
AND Customers.Region IN
(SELECT Customers.Region
FROM Customers
GROUP BY Customers.Region HAVING COUNT(Customers.Region)=1);
but it returns only 6.
The database is northwind. **Company name
here is the output
Old World Delicatessen
Let's Stop N Shop
Save-a-lot Markets
The Cracker Box
Rattlesnake Canyon Grocery
Split Rail Beer & Ale**
Upvotes: 0
Views: 1021
Reputation: 92805
Try this
SELECT CompanyName
FROM Customers
WHERE Country='USA' AND
Region NOT IN
(SELECT DISTINCT Region
FROM Employees
WHERE Region IS NOT NULL);
Output
CompanyName
----------------------------------------
Great Lakes Food Market
Hungry Coyote Import Store
Let's Stop N Shop
Lonesome Pine Restaurant
Old World Delicatessen
Rattlesnake Canyon Grocery
Save-a-lot Markets
Split Rail Beer & Ale
The Big Cheese
The Cracker Box
(10 row(s) affected)
In your your question you said that you need Company Name of all U.S.-based customers who are NOT located in the same state (or region) as any of the employees. But in your query you were trying to get regions from Customers table instead.
UPDATE: I believe that you know that but just in case:
The explicit check for NULL
values in the subquery (WHERE Region IS NOT NULL
) is crucial. Without it the query will run successfully but won't return any rows.
SELECT CompanyName
FROM Customers
WHERE Country='USA' AND
Region NOT IN
(SELECT DISTINCT Region
FROM Employees);
Output:
CompanyName
----------------------------------------
(0 row(s) affected)
I guess that exercise that you were trying to accomplish was meant to make sure that you know about NULLs in subqueries.
Upvotes: 4
Reputation: 125640
Your query does not check Employees
table at all! Check out that:
SELECT Customers.CompanyName, customers.Region
FROM Customers
WHERE Customers.Country='USA'
AND NOT EXISTS(SELECT 1 FROM Employees WHERE Employees.Region = Customers.Region)
or
SELECT Customers.CompanyName, customers.Region
FROM Customers
WHERE Customers.Country='USA'
AND Customers.Region NOT IN (SELECT DISTINCT Employees.Region FROM Employees WHERE Employees.Region IS NOT NULL)
Both queries return:
Great Lakes Food Market OR
Hungry Coyote Import Store OR
Let's Stop N Shop CA
Lonesome Pine Restaurant OR
Old World Delicatessen AK
Rattlesnake Canyon Grocery NM
Save-a-lot Markets ID
Split Rail Beer & Ale WY
The Big Cheese OR
The Cracker Box MT
Upvotes: 1