speed issue with query

Discussion in 'Databases' started by jred2002, Oct 24, 2007.

  1. #1
    I have this query -

    SELECT distinct FIPS, NAME FROM table1.dbo.view1 WHERE state_abbreviation = 'NY' and FIPS not in (SELECT FIPS FROM table1.dbo.view2 WHERE State_Abbreviation = 'NY' and order in (12345))

    It takes over a minute. The second view is big - like 8 million rows

    the first query -

    SELECT distinct FIPS, NAME FROM Table1.dbo.view1 WHERE state_abbreviation = 'NY'

    and the second query -

    SELECT FIPS FROM table1.dbo.view2 WHERE State_Abbreviation = 'NY' and order in (12345)

    take less than a second each - but put them both together and ass the "not in" and it take about a minute and a half.

    Any help would be greatly appreciated
     
    jred2002, Oct 24, 2007 IP
  2. benajnim

    benajnim Peon

    Messages:
    20
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    While perhaps not the most elegant solution, you could do a lazy-dba's "caching" of the results of this query if it doesn't need to be performed in real time (though you could update the results multiple times in an hour/day).

    insert into cache_table (select .....)

    You could cache the query that pulls out records where state = "NY" into your temp table, and reference the cache table in your Not In sub-query for a potentially workable "hybrid" solution.
     
    benajnim, Oct 24, 2007 IP
  3. jred2002

    jred2002 Well-Known Member

    Messages:
    160
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    103
    #3
    Thank you for the reply benajnim but I actually figured out a much faster way of doing it -

    SELECT distinct * FROM table1.dbo.view1
    left join (SELECT FIPS as fips1 FROM table1.dbo.view2
    WHERE State_Abbreviation = 'NY' and order in (12345))t3 on
    table1.dbo.view1.fips = t3.fips1
    WHERE state_abbreviation = 'NY' and t3.fips1 is null

    I had never used the left join before - but this only takes 1 second to run :D

    Thanks again
     
    jred2002, Oct 24, 2007 IP