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)
 Slow left outer join query

Author  Topic 

denis_the_thief
Aged Yak Warrior

596 Posts

Posted - 2012-03-24 : 09:48:16
Hi. I have 2 queries:

Query 1:

select * from
T1 left outer join T2 on T1.C1 = T2.C2
where T2.C3 = 1000


Query 2:

select * from
(
select * from
T1 left outer join T2 on T1.C1 = T2.C2
) as T
where C3 = 1000



So it is the same query but in Query 2, the filter is moved outside the main query. The problem is that Query 2 is very slow (Query 1 is very fast). I am very surprised at the speed difference since it is essentially the same query. When I change both queries to inner join, both are fast. The issue is that I wish to make a view here: select * from T1 left outer join T2 on T1.C1 = T2.C2

Let's assume I have proper indexes and stats are up to date etc...

Has anyone encountered anything similar or have any suggestions?


sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-03-24 : 10:13:55
They are interpreted differently by SQL. The first query is effectively an inner join because of the presence of the WHERE clause that has a column from T2. The first query will give the same results as this:
select * from
T1 INNER join T2 on T1.C1 = T2.C2
where T2.C3 = 1000
If you really want to do a left join only with rows from T2 where T2.C3 = 1000, do it like this:
select * from
T1 left outer join T2 on T1.C1 = T2.C2 AND T2.C3 = 1000
The inner query in the second example you posted is a real left join - which would preserve all the rows from the left table[/code]
Go to Top of Page

denis_the_thief
Aged Yak Warrior

596 Posts

Posted - 2012-03-24 : 10:27:58
Thanks. I think this means our SQL is not quite right...
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-03-24 : 15:39:22
see this article

http://weblogs.sqlteam.com/jeffs/archive/2007/05/14/criteria-on-outer-joined-tables.aspx

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -