Skip to content
Advertisement

Getting an empty result with ‘AND’ operation and wrong result with ‘OR’ operation in SQL

I have two tables and I want to find out the customer_id and customer_name of all customers who bought product A and B both.

In this example only the customers with id 1 and 3 have bought both the product A and B.

To find that i wrote this code –

When I am doing this I am getting an empty result.

So tried to use OR –

output –

Based on OR it is working right but I am still not getting the result I am trying to find. Because customer with id 2 only bought A and not Product B. And Using AND bringing me an empty result. I always feel confused with AND and OR operations. can someone help?

Advertisement

Answer

If you want both use aggregation:

Note: This assumes that the data could have multiple rows for a customer and product. If that is not possible, just use count(*) = 2 for performance reasons.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement