简体   繁体   中英

Left outer Join query optimization

I am not so advanced sql user. Could you please review my following query is it optimal ? or I can do something more more optimized and more readable?

      select  Distinct  DT.Station  , DT.Slot , DT.SubSlot, DT.CompID , CL.CompName
            from    (
                        select  Station, Slot, SubSlot, CompID
                        from    DeTrace
                        where   DeviceID = '1151579773'     
                    ) as DT 
            Left outer CList as CL  
                  on  DT.CompID = CL.CompID 
                  where CL.CompName = '9234220'
                  order by CompName 

Thanks for help.

It is easier to read like this:

 select  Distinct  DT.Station  , DT.Slot , DT.SubSlot, DT.CompID , CL.CompName
            from  DeTrace DT    
            Left outer join CList as CL  
                  on  DT.CompID = CL.CompID 
                  where CL.CompName = '9234220'
                    and DT.DeviceID = '1151579773'
                  order by CompName 

The optimiser should be able to perform this query as efficiently as yours, but you should check the query execution plan just to be sure.

Why not just:

SELECT DISTINCT DT.Station  , DT.Slot , DT.SubSlot, DT.CompID , CL.CompName
FROM DeTrace DT
LEFT OUTER JOIN CList CL ON DT.CompID = CL.CompID
                       AND DT.DeviceID = '1151579773'
                       AND CL.CompName = '9234220'
ORDER BY CL.CompName

I think you don't need subquery. Check below:

select  Distinct  DT.Station  , DT.Slot , DT.SubSlot, DT.CompID , CL.CompName            
from    DeTrace as DT 
Left outer CList as CL  
on  DT.CompID = CL.CompID 
where CL.CompName = '9234220' and DeviceID = '1151579773'     
            order by CompName 

I like this way best:

SELECT  DISTINCT
        DeTrace.Station,
        DeTrace.Slot,
        DeTrace.SubSlot,
        DeTrace.CompID,
        CL.CompName
    FROM
        DeTrace
    LEFT OUTER JOIN
        CList AS CL ON
            DeTrace.CompID = CL.CompID
    WHERE
        DeviceID = '1151579773' AND
        CL.CompName = '9234220'
    ORDER BY
        CL.CompName
select  Distinct  DT.Station  , DT.Slot , DT.SubSlot, DT.CompID , CL.CompName                  
from    DeTrace DT
Left outer join CList as CL  
          on  DT.CompID = CL.CompID 
where DT.DeviceID = '1151579773' 
and  CL.CompName = '9234220'    
order by CL.CompName

The Sql Server Cost Based Optimizer should be able to determine the most efficient order in which to apply the conditions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM