Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Show items NOT in another table

Author  Topic 

aberbotimue
Starting Member

26 Posts

Posted - 2009-10-13 : 13:02:53
I'm sure it's a simple one, but I have built a good 15 - 20 queries, and non have done the trick, I am resorting to asking..

I have a table full of items.

I have a table full of locations of those items..

I want a query that lists all the items in the first table, that arn't in the second..

Its that simple, but I can't figure it!!

any help would be loved!

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2009-10-13 : 13:10:24
You can use a LEFT JOIN or NOT EXISTS.

SELECT *
FROM items i
LEFT JOIN locations l
ON i.location_id = l.location_id
WHERE l.location_id IS NULL

SELECT *
FROM items i
WHERE NOT EXISTS (SELECT * FROM locations l WHERE l.location_id = i.location_id)

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog

"Let's begin with the premise that everything you've done up until this point is wrong."
Go to Top of Page

X002548
Not Just a Number

15586 Posts

Posted - 2009-10-13 : 14:21:07
SELECT 'Item' AS Source, location_id From Items
UNION ALL
SELECT 'Locations' AS Source location_id From Locations
GROUP BY location_id
HAVING COUNT(*) <> 2



Brett

8-)

Hint: Want your questions answered fast? Follow the direction in this link
http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx

Add yourself!
http://www.frappr.com/sqlteam



Go to Top of Page

aberbotimue
Starting Member

26 Posts

Posted - 2009-10-14 : 14:08:39
Thanks Guys.. WOrked like a dream!! and three different versions to choose from!! shows how bad I am at this! couln't eveb get one to work!
Go to Top of Page

X002548
Not Just a Number

15586 Posts

Posted - 2009-10-14 : 14:30:56
do a showplan on them...is the column indexed?



Brett

8-)

Hint: Want your questions answered fast? Follow the direction in this link
http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx

Add yourself!
http://www.frappr.com/sqlteam



Go to Top of Page
   

- Advertisement -