Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL IF EXISTS with OR Condition

I am facing a performance issue with a SQL statement. I have noticed a performance degradation in one SQL statement in one of a procedure.

SQL Statement:

IF EXISTS(SELECT TOP 1 FROM TABLE1 WHERE COLUMN1 = 'XYZ')  OR @ISALLOWED = 1
BEGIN
    -- SQL Statements
END

I couldn't able to understand why OR statement with IF Exists statement is causing performance issue in above query. Because if I rewrite the above statement like this:

DECLARE @ISVALUEEXISTS BIT
SET @ISVALUEEXISTS = 0

IF EXISTS(SELECT TOP 1 FROM TABLE1 WHERE COLUMN1 = 'XYZ')
    SET @ISVALUEEXISTS = 1

IF (@ISVALUEEXISTS = 1 OR @ISALLOWED = 1 )
BEGIN
     --SQL Statements
END

Then performance issue is gone. So, I'm couldn't able to understand how and why OR condition with IF Exists statement is causing problem.

Anyone has any idea about this?

like image 590
Geeky Ninja Avatar asked Dec 10 '25 00:12

Geeky Ninja


1 Answers

If you have this query inside stored procedure this could happen because of parameter sniffing.

Try something like this to check it:

declare @ISALLOWED_internal
select @ISALLOWED_internal = @ISALLOWED

IF EXISTS(SELECT TOP 1 FROM TABLE1 WHERE COLUMN1 = 'XYZ')  OR  @ISALLOWED_internal = 1
BEGIN
    -- SQL Statements
END
like image 57
Roman Pekar Avatar answered Dec 12 '25 17:12

Roman Pekar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!