SQL Server - Query Execution Plan For Conditional Statements
-
08-07-2019 - |
Question
How do conditional statements (like IF ... ELSE) affect the query execution plan in SQL Server (2005 and above)?
Can conditional statements cause poor execution plans, and are there any form of conditionals you need to be wary of when considering performance?
** Edited to add ** :
I'm specifically referring to the cached query execution plan. For instance, when caching the query execution plan in the instance below, are two execution plans cached for each of the outcomes of the conditional?
DECLARE @condition BIT
IF @condition = 1
BEGIN
SELECT * from ...
END
ELSE
BEGIN
SELECT * from ..
END
Solution
You'll get plan recompiles often with that approach. I generally try to split them up, so you end up with:
DECLARE @condition BIT
IF @condition = 1
BEGIN
EXEC MyProc1
END
ELSE
BEGIN
EXEC MyProc2
END
This way there's no difference to the end users, and MyProc1 & 2 get their own, proper cached execution plans. One procedure, one query.