Question

I want to the EXISTS operator to list the customer names who have no orders

So I have two Tables (as shown below) One named Customer which holds CustomerName and CustomerID and another named orders which hold CustomerID as well as OrderID. I was trying to

SELECT CustomerName, CustomerID FROM Customer WHERE EXISTS (

SELECT CustomerID, OrderID FROM orders WHERE OrderID <> CustomerID );

but it's not working the way I wanted it to.

Was it helpful?

Solution

One way you can do this is by using the NOT EXISTS syntax. Personally, it makes more sense to me. I think this query would work for you:

Select CustomerName
, CustomerID 
FROM Customer C 
WHERE NOT EXISTS(Select 1 FROM Orders O where C.CustomerId = O.CustomerId)

OTHER TIPS

"NOT EXISTS" is a notoriously poor performer (unless MySQL has come up with some kind of optimization for it) because if forces a full-table scan.

The standard workaround is to use outer joins. Not intuitive, so it should be commented for future maintainers.

SELECT CustomerName, CustomerID from Customer C LEFT JOIN Orders O ON C.CustomerID = O.CustomerID WHERE O.CustomerID IS NULL

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top