Search code examples
sqlsql-serverquery-optimization

SQL Optimization - where not exists self join


Please provide advice on how to optimize this sql procedure... the where not exists subselect is my main issue. I have been told I can get a 40% performance increase.

   insert into #tmpTable (intID3,intID4,intID5,intID6, 
          StaticDate,NewDate, 
          [Description],Change,intSort) 
   select distinct 
          '' as intID3,           
          intID4,
          intID5, 
          intID6, 
          @dteDate1 as StaticDate, 
          '' as NewDate,           
          '16 character str' as [Description], 
          0 as Movement,
          0 as intSort

   from #tmpTable j 
   where not exists ( 
        select 
               1 
        from #tmpTable x 
        where
               x.intID1 = j.intID1 
               and x.intID2 = j.intID2 
               and x.[Description] = '16 character str' 
   ) 

Solution

  • Try with the below query.

     INSERT INTO #tmpTable2 
         (intID3,intID4,intID5,intID6, 
          StaticDate,NewDate, 
          [Description],Change,intSort)
      SELECT DISTINCT 
          '' as intID3,           
          j.intID4,
          j.intID5, 
          j.intID6, 
          @dteDate1 as StaticDate, 
          '' as NewDate,           
          '16 character str' as [Description], 
          0 as Movement,
          0 as intSort
     FROM #tmpTable j 
           LEFT JOIN #tmpTable x  
                 ON  x.intID1 = j.intID1 
                      AND x.intID2 = j.intID2 
                      AND x.[Description] = '16 character str' 
     WHERE x.intID1 IS NULL