Query is using DISTINCT and seems to take long time to execute

  • The purpose of below query is to get the

    DISTINCT name from myTable and it should not be in myAnotherTable for productCode = 'SomeProduct'

    Select distinct name from myTable

    where name NOT IN

    (select productName from myAnotherTable

    where productCode = 'SomeProduct')

    order by 1

    myTable has some 300,000 rows

    select DISTINCT name from myTable alone gives 238 rows(with one NULL entry)

    subquery returns - 13 rows

    Is there any way to improve the performance of this query?

    -

    KB

    Thanks,
    Santhosh


    Human Knowledge Belongs To The World !!

  • Except might be better

    Select name from myTable

    except

    select productName from myAnotherTable

    where productCode = 'SomeProduct'



    Clear Sky SQL
    My Blog[/url]

  • Did you try EXISTS?

    Select distinct name

    from myTable

    where NOT EXISTS (

    select 1

    from myAnotherTable

    where productCode = 'SomeProduct'

    AND productName = myTable.Name

    )

    order by 1

    -- Gianluca Sartori

  • Select name from myTable

    except

    select productName from myAnotherTable

    where productCode = 'SomeProduct'

    Gianluca Sartori (9/11/2009)


    Did you try EXISTS?

    Select distinct name

    from myTable

    where NOT EXISTS (

    select 1

    from myAnotherTable

    where productCode = 'SomeProduct'

    AND productName = myTable.Name

    )

    order by 1

    Yes, I tried both, seems both are running faster.

    I do not have permissions to see the execution plan. But better than NOT IN.

    -

    KB

    Thanks,
    Santhosh


    Human Knowledge Belongs To The World !!

  • KB (9/11/2009)

    Yes, I tried both, seems both are running faster.

    I do not have permissions to see the execution plan. But better than NOT IN.

    Glad of that.

    TBH , i didnt know that permissions to view the plan can be restricted.

    I would certainly argue that its essential to see the plan.



    Clear Sky SQL
    My Blog[/url]

Viewing 5 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic. Login to reply