tags:

views:

47

answers:

3

I have 2 tables (Orders, OrderItems) that are related based on a column OrderID. I need to find all Orders that do not have any OrderItems.

+3  A: 
Select * From Orders Where OrderID not in (Select Distinct OrderID From OrderItems)
Mark Brittingham
+1  A: 

try with LEFT EXCEPTION JOIN

select *
from Orders
LEFT EXCEPTION JOIN OrderItems ON ...
Danny T.
+1 - Cool - haven't seen that one before.
Mark Brittingham
+6  A: 

The following joins the tables, then selects those without any order items. The join is thought to be more efficient than using `IN'.

select *
from
    Orders O
    left outer join OrderItems I
    on I.OrderId = O.Id
where
    I.Id is null
Aaron
That's what I ended up doing, thanks
Slee
Aaron - I can imagine ways that a left outer join would be more efficient but do you have a specific reference for your assertion? I'd probably avoid using this construct because of the additional complexity but it might be appropriate (for me) for large datasets if there is a clear performance difference.
Mark Brittingham
I do not have a specific reference; it is just an assertion I've heard from colleagues and one that I have often found to be true in my own experiences. This solution is not necessarily the best for every case, so it is best to try each and check out their respective execution plans and decide which is best from there.
Aaron
After some searching, I found a lot of agreement with my thoughts on the subject. Here is a relevant link: http://sqlserverpedia.com/blog/sql-server-bloggers/using-joins-instead-of-sub-queries-a-case-study/
Aaron
Thanks Aaron! Very useful reference - I appreciate the effort it took to look it up.
Mark Brittingham