• subscribe
January 25, 2006 12:00 AM

Catch That Bug!

SQL Server Pro
InstantDoc ID #48767
Downloads
48767.zip

Welcome to a new challenge called "Catch That Bug!" Each month, I'll present T-SQL code that has a bug, and your challenge is to find it. I'll provide the solution the following month, along with a new challenge. Sometimes, you'll be able to research past magazine articles to find the cause of the bug. Other times, you'll have to figure out the solution on your own. Here's your first "Catch That Bug!" challenge.

From the Customers and Orders tables that you create and populate by running the code in Listing A, you need to return the details of customers who made orders. You build the following query to return the details:

SELECT custid,
  custname 
FROM dbo.Customers
WHERE custid 
  IN(SELECT custid
  FROM dbo.Orders); 

Given the sample data in the Customers and Orders tables, you probably expect your query to return customers A and B. Instead, you get back all customers, including those who made no orders. Why?



ARTICLE TOOLS

Comments
  • Craig
    6 years ago
    Mar 02, 2006

    Sorry timoverlund The sub query is failing to resolve custid from orders and so finds custid in the "parent" query - in the same way as would be required to resolve a parameter passed to the sub query.

    Damm good problem though!

  • Tim
    6 years ago
    Jan 27, 2006

    The bug is the custid instead of customerid in dbo.Orders. This means the subquery errors out which causes the WHERE filter to not filter anything, returning all rows in dbo.Customers. Once the proper column name is used, the filter works properly. Not sure why the query as a whole doesn't simple fail when the subquery contains an error though. That would seem a more logical approach.

You must log on before posting a comment.

Are you a new visitor? Register Here