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
 SQL Server 2008 Forums
 Transact-SQL (2008)
 LEFT JOIN with Where clause in Select

Author  Topic 

ujjaval
Posting Yak Master

108 Posts

Posted - 2011-11-03 : 03:04:18
Hi,

I have two tables, #TableA(in memory temp table) and TableB(db table) both having same columns.
#TableA does not have primary key restriction on it.

Now, I have following select statement


SELECT new.*
FROM #TableA AS new
LEFT JOIN TableB AS old
ON new.[ColId] = old.[ColId]
WHERE old.[ColId] IS NULL


TableA has 298 rows
TableB has 298 rows

But when I run above query I get 4 specific rows.
Now when I remove that Where clause and just run following select

SELECT new.*
FROM #TableA AS new
LEFT JOIN TableB AS old
ON new.[ColId] = old.[ColId]


I get 298 rows again.

Can anyone explain or throw some light on what is happening in this select statement with Where clause?

[TableB].[ColId] is a primary key in the table and has no row with NULL in ColId column.

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2011-11-03 : 03:16:48
That's how an outer join works. A left outer join means you get all of the matches between the two tables, and when there isn't a match you'll see NULL in the right table. In your case, TableB is the right table.

Your first query is show you only the unmatching rows.

Matching/unmatching here means ColId only, not the entire row.

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

Subscribe to my blog
Go to Top of Page

ujjaval
Posting Yak Master

108 Posts

Posted - 2011-11-03 : 20:12:17
Thanks Tara..

I was caught with Where clause and scratching my head, forgetting the outerjoin bit.

Regards,

quote:
Originally posted by tkizer

That's how an outer join works. A left outer join means you get all of the matches between the two tables, and when there isn't a match you'll see NULL in the right table. In your case, TableB is the right table.

Your first query is show you only the unmatching rows.

Matching/unmatching here means ColId only, not the entire row.

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

Subscribe to my blog

Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2011-11-03 : 20:58:59
You're welcome, glad to help.

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

Subscribe to my blog
Go to Top of Page
   

- Advertisement -