I have the following query:
SELECT I.InsuranceID
FROM Insurance I
INNER JOIN JobDetail JD ON I.AccountID = JD.AccountID
WHERE I.InsuranceLookupID IS NULL
AND JD.JobID = 28
It executes in about a second. When used as a subquery as follows:
IF EXISTS(
SELECT I.InsuranceID
FROM Insurance I
INNER JOIN JobDetail JD ON I.AccountID = JD.AccountID
WHERE I.InsuranceLookupID IS NULL
AND JD.JobID = 28
)
SELECT 1
ELSE
SELECT 0
It takes 90 seconds. It's my understanding that EXISTS is supposed to be optimized to stop after finding the first record. Why would this take longer?