Search code examples
sqlsql-serverquery-performance

Performance tuning of query


I have a query which takes a long time to run. It is probably because I used too many isnulls in the join condition. How can I optimise it by removing the isnull?

Is there any alternate way without updating the table? The query is given below:

 select pos.C_id
    ,pos.s_id
    ,pos.A_id
    ,pos.Ad_id
    ,pos.Pr_id
    ,pos.prog_id
    ,pos.port_id
    ,pos.o_type
    ,pos.o_id
    ,pos.s_id
    ,pos.c_id
    ,pos.s_type_id
    ,pos.s_type
    ,pos.e_date
    ,pos.mv
    ,0 is_pub
    , 1 is_adj           
    ,pos.is_unsup
    ,getdate() date
    ,getdate() timestamp
    from #temp pos
    left join acc c with(nolock) ON pos._id = c.c_id
    AND pos.account_id = c.account_id
    AND isnull(pos.Pr_id,0) = isnull(c.pr_id,0)
    AND isnull(pos.prog_id,0) = isnull(c.prog_id,0)
    AND isnull(pos.port_id,0) = isnull(c.port_id,0)
    and isnull(pos.style_type_id,0)=isnull(c.s_type_id,0)
    AND pos.s_id = c._id
    AND pos.c_id = c.c_id
    AND pos.s_type = c.s_type
    AND pos.is_unsup = c.is_uns
    AND pos.is_pub = 1
    where c.a_id is null

Solution

  • try using

    AND (pos.Pr_id = c.pr_id OR (pos.Pr_id IS NULL AND c.pr_id IS NULL))
    

    instead of

    AND ISNULL(pos.Pr_id,0) = ISNULL(c.pr_id,0)
    

    IS NULL is more efficient than ISNULL