I have an SQL query that takes about 30 seconds to run, which returns 1 record. The function used in CROSS APPLY is instantly launched using the BrandId of this entry.
SELECT b.BrandId, b.Name, ah.Type, c.ContactEmails, c.ContactNumbers, c.ContactLinks FROM @IdsToFilterBy ids JOIN dbo.AccountHandler ah ON ah.AccountHandlerId = ids.Id JOIN dbo.Brand b ON ah.RepresentedByBrandId = b.BrandId CROSS APPLY dbo.[fn_GetBrandContactDetails](b.BrandId) AS c
However, if I just changed the table, I get BrandId for CROSS APPLY ..
SELECT b.BrandId, b.Name, ah.Type, c.ContactEmails, c.ContactNumbers, c.ContactLinks FROM @IdsToFilterBy ids JOIN dbo.AccountHandler ah ON ah.AccountHandlerId = ids.Id JOIN dbo.Brand b ON ah.RepresentedByBrandId = b.BrandId CROSS APPLY dbo.[fn_GetBrandContactDetails](ah.RepresentedByBrandId) AS c <-- change here
now the request takes only 2 seconds. When I join dbo.Brand b ON cah.RepresentedByBrandId = b.BrandId , I expect them to be the same.
Can someone explain why there is a huge difference in performance?
UPDATE
The difference is that CROSS APPLY works throughout the Brand table when I use b.BrandId and the entire AccountHandler table when I use ah.RepresentedByBrandId. The AccountHandler table is significantly smaller.
However, I expected CROSS APPLY to work only on the results of JOINs, which is one 1 record. Is this possible, or did I miss an understanding of CROSS APPLY?
sql sql-server
Magpie
source share