Link to home
Start Free TrialLog in
Avatar of countrymeister
countrymeister

asked on

SQL subquery with regard to performance

I have a table Order and OrderHistory

Order

ID
Verified
Reason


OrderHistory
ID
ParentID
INACTIVEDATE

I need to update the Verified field to C (Closed)
where the current date is greater or equal the ParentID order INACTIVEDATE .

Currently I have Orders that have the Verified value as "A" Active, when the Parent Order is closed.

I have the following query, and would like to know if this can be tweaked to improve performance.
For example should I dump all Inactive Parent Orders into a temporary table and then use that for my subquery qualification.

update    O set        
 Verified             =     'C'        
 ,O.Reason     =   case        
         when len(O.Reason) = 0 then 'Inactive Parent Order'        
         else left(O.Reason + ', Inactive Parent Order', 255)        
      end        
from dbo.Orders O        
join dbo.OrderHistory OH        
 on O.ID = OH.ID
and isnull(OH.ParentID,'') != ''
and OH.ParentID in
(select distinct PA.ParentID from dbo.dbo.OrderHistory PA
where getDate() >= case when isdate(PA.INACTIVEDATE) = 1 then convert(datetime,PA.INACTIVEDATE)
                                          else '01/01/9999' end                          
                                          and isnull(PA.ParentID,'') != ''      
)          


update    O set        
 Verified             =     'C'        
 ,O.Reason     =   case        
         when len(O.Reason) = 0 then 'Inactive Parent Order'        
         else left(O.Reason + ', Inactive Parent Order', 255)        
      end        
from dbo.Orders O        
join dbo.OrderHistory OH        
 on O.ID = OH.ID
and isnull(OH.ParentID,'') != ''
and OH.ParentID in 
(select distinct PA.ParentID from dbo.dbo.OrderHistory PA 
where getDate() >= case when isdate(PA.INACTIVEDATE) = 1 then convert(datetime,PA.INACTIVEDATE) 
							else '01/01/9999' end                           
							and isnull(PA.ParentID,'') != ''	
)

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of DBAduck - Ben Miller
DBAduck - Ben Miller
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of sampipes
sampipes

One thing that would increase perfomance a lot would be to replace the
and OH.ParentID in (....)
with

and      exists      (SELECT 1
                        from dbo.OrderHistory PA
                        where getDate() >= case
                                                      when isdate(PA.INACTIVEDATE) = 1 then convert(datetime,PA.INACTIVEDATE)
                                    else '01/01/9999' end
                        AND PA.ParentID = OH.ParentID)