How to find all customers who didn't place an order?

时间:2015-06-15 14:45:31

标签: sql sql-server

I am new to stackoverflow, I recently went through an interview as graduate developer, and I was asked a question regarding SQL.

Given two table customers and orders, how to find all cusomers who didn't place an order. Can someone tell me what would be a query to achieve this?

--Forgot to mention that I was asked to use JOIN operator for this.

EDIT: I could not find answer to this question as this was technical as well as logical. Therefore, I think my question is different from the one identified as a duplicate.

2 个答案:

答案 0 :(得分:3)

SELECT  c.CustomerId
        ,Name
FROM    dbo.Customers c 
            LEFT JOIN dbo.Orders o ON o.CustomerId = c.CustomerId
WHERE   OrderId IS NULL

答案 1 :(得分:2)

This translates into a Correlated Subquery using EXISTS:

select * 
from customers as c
where not exists
 ( select * from orders as o
   where c.customer_id = o.customer_id)

No order exists for a given customer_id