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 2005 Forums
 Transact-SQL (2005)
 Why does this nested select/in take so long?

Author  Topic 

bastian74
Starting Member

2 Posts

Posted - 2010-10-11 : 19:19:43
If I do
select Key from B where var1=test I get results immediately.
However if I do
select A.Name from A where A.Key in (select Key from B where var1=test)
It takes a ton of time. I let it go 15 minutes, but it's rediculous. The subquery itself only takes 0.01 seconds to run.

Is it doing something really stupid like running the subquery for every record of the parent query?

Bustaz Kool
Master Smack Fu Yak Hacker

1834 Posts

Posted - 2010-10-11 : 19:26:21
If you look at the execution plan, does it look like it is trying to join the two tables? If so, what kind of indexing do you have on the A.Key field?

=======================================
In all life one should comfort the afflicted, but verily, also, one should afflict the comfortable, and especially when they are comfortably, contentedly, even happily wrong. -John Kenneth Galbraith, economist (1908-2006)
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-10-11 : 19:36:48
How many rows is it going to return?

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

Subscribe to my blog
Go to Top of Page

bastian74
Starting Member

2 Posts

Posted - 2010-10-11 : 19:59:01
Each table is millions of rows, but the total number of rows returned is only a dozen or so

I decided to do the nested join as a temp table that runs before the primary query, then my nested select is just calling the temp table isntead of a select

This complets in moments.

To me it seems that the nested select is being run against every row of the parent query.
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2010-10-11 : 20:01:06
I'd just switch it to a join rather than using a temp table. You probably either had a very bad execution plan or your query was being blocked by some other process.

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 -