2

I have a question about how to retrieve data from one customer's order table (Oracle) like this:

id   customer cake          top   
1    001      chocolate     cream
2    002      chocolate     jam
3    002      vanilla       cream
4    003      banana        cream

I want to know all orders from customers whose order includes chocolate cake.

The right result should be

id   customer cake          top   
1    001      chocolate     cream
2    002      chocolate     jam
3    002      vanilla       cream

I could do this by 2 separate queries in SQL, but is there any way to do this in a single query?

Many Thanks!

1
  • Which RDBMS is this for? Please add a tag to specify whether you're using mysql, postgresql, sql-server, oracle or db2 - or something else entirely. Commented Jan 29, 2016 at 6:21

5 Answers 5

2

you should use an sub-query to get the customers:

select * from order where customer in (
  select distinct customer from order where cake = 'chocolate'
)
Sign up to request clarification or add additional context in comments.

Comments

1

A subquery that selects the distinct customers whose order include chocolate would work :

select 
  * 
from 
  order 
where 
  customer 
in (select 
      distinct customer 
    from 
      order 
    where 
      cake = 'chocolate')

Comments

1

You can do this using inner queries.

SELECT * FROM ORDER WHERE CUSTOMER IN (
    SELECT CUSTOMER FROM ORDER WHERE cake = 'chocolate'
 )

Comments

1

Something like this should work:

SELECT *
FROM customers
WHERE EXISTS (SELECT 1
              FROM order_details
              WHERE customers.id = order_details.customer_id
              AND cake = 'chocolate');

Edited: added the chocolate cake condition.

3 Comments

SELECT 1 will select 1, I suspect you meant SELECT TOP 1?
@wentimo No, I dont mean top 1. The way i wrote it will select 1, yes. but that is enough to locate the row and prove its existence. since we don't need any fields from the Exists clause, using a 1 in place of * makes it runs faster and does the same thing.
Ah nifty, I didn't know about this particular pattern as a solution. Thanks for pointing it out.
0
SELECT * FROM ORDER O1 WHERE EXISTS (
    SELECT NULL FROM ORDER O2 WHERE O1.ID = O2.ID AND cake = 'chocolate'
 )

You may try a variation of this subquery.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.