Here is my query, can anyone see any way to make this more efficient so it doesn't time out? I'm using Exacttarget (Salesforce Marketing Cloud). It has a 30 minute timeout limit. I've tried moving things around but it always seems to error. I'm kind of a beginner with SQL but I've been hitting it fairly hard the last week. My query is below. THanks!
SELECT DISTINCT c.Email, c.FName
FROM ENT.Contacts c WITH(NOLOCK)
INNER JOIN ENT.RegistrationData r WITH(NOLOCK)
ON c.Email = r.RegistrationContactEmail
LEFT Join ENT._Subscribers s WITH(NOLOCK)
ON c.Email = s.SubscriberKey
AND s.status NOT IN ('unsubscribed','held')
WHERE
(
(
(
(
r.RegistrationEmailOptStatus = '1' AND
r.RegistrationEventType = 'Wedding' AND
r.RegistrationEventRole IN ('Bride','Other','Bridesmaid','Mother Of the Bride') AND
r.RegistrationCountry IN ('USA') AND
r.RegistrationEventDate < '2014-05-31'
)
OR
(
r.RegistrationEmailOptStatus = '1' AND
r.RegistrationEventType = 'Prom' AND
r.RegistrationEventRole ='Prom' AND
r.RegistrationCountry IN ('USA') AND
r.RegistrationEventDate BETWEEN '2014-01-01' AND '2015-12-31'
)
)
AND
(
(
c.Email IN
(
SELECT DISTINCT
s.SubscriberKey AS Email
FROM
_Open s
WHERE
datediff(mm,s.EventDate, getdate()) <= 3
)
)
OR
(
c.Email IN
(
SELECT DISTINCT
s.SubscriberKey AS Email
FROM
_Click s
WHERE
datediff(mm,s.EventDate, getdate()) <= 3
)
)
)
)
OR
(
r.RegistrationEmailOptStatus = '1' AND
r.RegistrationEventType = 'Wedding' AND
r.RegistrationEventRole IN ('Bride','Other','Bridesmaid','Mother Of the Bride') AND
r.RegistrationCountry IN ('USA') AND
r.RegistrationEventDate BETWEEN '2015-05-01' AND '2015-05-31'
)
)
I'll take a shot. There maybe some minor stuff, but the only thing that looks to me like it should make the query spin a long time is
There are two issues in there. First you are doing date math a bajillion times and second using IN (SELECT ...) here is almost certainly inefficient.
To address the first, calculate a single test date to and use that. For the second prefer checking with EXISTS.
...
You could also probably unwind the EXISTS and use joins to _Open and _Click, but that feels more complex.
Give this a shot and let us know if it helps.