Solved

Need to select all rows from table1 that do not have a matching key in table 2

Posted on 2008-09-30
4
226 Views
Last Modified: 2010-04-21
I have two tables ie Customers and Orders

I need to Select all customers for which there are no orders.

ie. Show the CustomerID for all orders where the CustomerID in the Customers table s not found in the CustomerID of the Orders table.
What is the correct SQL syntax ?
Thanks,
0
Comment
Question by:Dovberman
4 Comments
 
LVL 11

Accepted Solution

by:
aaronakin earned 125 total points
ID: 22605551
SELECT *
  FROM Customers
  WHERE CustomerID NOT IN (SELECT CustomerID FROM Orders)
0
 
LVL 60

Assisted Solution

by:chapmandew
chapmandew earned 125 total points
ID: 22605560
or like this

select * from customers c where not exists(select 1 from orders o where o.customerid = c.customerid)
0
 
LVL 5

Expert Comment

by:adlink_la
ID: 22605771
If I read that right, you want customers that have no Orders?
SELECT CustomerID

FROM Customers

EXCEPT

SELECT CustomerID 

FROM Orders

Open in new window

0
 

Author Closing Comment

by:Dovberman
ID: 31501551
aaronikin and chapmandew split the points. Both returned 38 rows. adlink la returned 32 rows. Thanks to all.
0

Featured Post

Complete Microsoft Windows PC® & Mac Backup

Backup and recovery solutions to protect all your PCs & Mac– on-premises or in remote locations. Acronis backs up entire PC or Mac with patented reliable disk imaging technology and you will be able to restore workstations to a new, dissimilar hardware in minutes.

Join & Write a Comment

JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now