Search code examples
performancesql-server-2012projection

SQL Select query Performance improvement


I've a bunch of queries like this :

-- get all data that exists in source but not yet in destination
SELECT 
*
INTO #temp
FROM source T010T
WHERE NOT EXISTS
                (
                SELECT TOP 1 1 FROM destination P510T
                WHERE WH_CD = T010T.WH_CD  
                AND   POS_NO = T010T.POS_NO 
                AND   SLIP_NO = T010T.TRAN_NO
                AND   OPE_DATE = T010T.SL_REC_DATE 
                ) 
-- process the data 
....
-- insert data into destination 
Insert into destination select * From #temp

I'm wondering will this way of approach will affect the performance? Because I haven't got the real data to test and this is running locally so I'm kind of scared that when put into reality, those queries will be a pain in the a@@!

Is there any better alternatives?

p/s : columns on both table used in the comparison are all primary keys primarykey(wh_cd,pos_no,slip_no,ope_date) ...


Solution

  • Try with Left Join instead:

    SELECT 
    *
    INTO #temp
    FROM source T010T
    LEFT JOIN destination P510T
                    ON    WH_CD = T010T.WH_CD  
                    AND   POS_NO = T010T.POS_NO 
                    AND   SLIP_NO = T010T.TRAN_NO
                    AND   OPE_DATE = T010T.SL_REC_DATE 
    WHERE P510T.WH_CD IS NULL