views:

27

answers:

2

Hi,

I am running the query below on a table with around 100k rows in it using a NOT IN and the performance is terrible. Is there another way of achieving the same result?

SELECT c.Id, c.Name, c.address, c.town,
c.county, c.postcode, FROM contractor AS c
inner join Order w
on w.Id = c.Id WHERE (c.valid = 1) and c.Id not in
(select w.Id from Order w) ORDER BY c.Name ASC

Thanks

A: 

I personally can't see further improvement to your code except that you might want to add indexing to your fields. The general rule is to add index to the columns you use in your WHERE clause.

Sarfraz
+2  A: 

You seem to have a redundant inner join to Order.
I believe following query would yield the same results and might improve performance.

SELECT  c.Id
        , c.Name
        , c.address
        , c.town
        , c.county
        , c.postcode
FROM    contractor AS c 
        left outer join Order w on w.Id = c.Id 
WHERE   (c.valid = 1) 
        and w.Id IS NULL
ORDER BY 
        c.Name ASC 
Lieven
I think this is what the TS wanted, +1.
Lex
Hi, Thanks for your suggestion. Unfortunately it is still running as i speak (2-3 minutes)... Is there a way to use a NOT EXISTS?
It's probably slow because you haven't indexed your columns. Put an index on the c.Id and w.Id column and you should be good to go.
Lex
As Lex said, you probably need to index you columns. You should take a look at the query plan for confirmation on this.
Lieven