Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi

I have this query and taking so much time to run , is there any way i can improve it , with creating any new views ,,, i can`t create temp db tables as they are avoid by DBA because of load on server


Thanks
Posted
Updated 19-Feb-15 9:40am
v3
Comments
Tomas Takac 17-Feb-15 9:29am    
The two nested SELECT-WHERE-IN look suspicious but the main problem IMO is the Convert/Cast in of opentime. What is the datatype of opentime? Why do you need to cast it and format it? This prevents the query engine from using indexes on that column.
saad88 17-Feb-15 10:09am    
hi tomas , the opentime is datetime fields .... i am using these format because i have date and time as yyyy-mm-dd 00:00:0000 and i only want to report as dd-mm-yyyy and no time
saad88 17-Feb-15 13:09pm    
thanks a lot tomas for solution ... really appreciate
PIEBALDconsult 17-Feb-15 9:49am    
I agree with Tomas. Eliminate the CAST and the CONVERT. Avoid subqueries, especially with an IN, and certainly never nest them -- learn to use JOINs. Also remove the FORMATs, formatting is not the job of the SQL, it's a job for the presentation layer.
John C Rayan 17-Feb-15 10:10am    
can you turn on execution plan and show us the plan?

1 solution

Try this:
SQL
select
    o.email as eml_addr,
    max(cl.clicktime) as lst_clk_mnth,
    max(o.opentime) as lst_opn_mnth
from 
    [open] o
    inner join view_mailing m on o.mailingid=m.mailingid
    inner join view_campaign c on c.campaignid=m.campaignid
    left join click cl on o.mailingid=cl.mailingid and o.email=cl.email
    inner join client c1 on c1.clientid = c.clientid
    inner join client c2 on c2.sameclient = c1.sameclient
where 
    c2.clientid = 219
    AND o.opentime >= '20130826'
group by
    o.email;

1) distinct is not needed
2) with(nolock) - don't use hints unless you know what you are doing and what are the consequences
3) no formats in select list - don't format data in the database
4) cast & convert in where - not needed
5) rewrite nested SELECT-WHERE-IN as inner joins
6) check if there are indexes on PK and FK columns
7) view_mailing & view_campaign - if these are really views look inside them and check for possible performance killers
 
Share this answer
 
Comments
PIEBALDconsult 17-Feb-15 18:16pm    
Actually I wouldn't put an INNER JOIN after an LEFT (OUTER) JOIN -- I have had trouble that way.
Tomas Takac 18-Feb-15 1:45am    
I don't think it matters in this case. Because the additional inner joins are on view_campaign, not on the "left joined" click. But I agree if you chain joins like inner-left-inner then the results are usually not what people expect.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900