Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql Excution Plan Shows Different result for same inputs

declare @name varchar(156)
set @name ='sara'
--Query 1:
SELECT [PNAME]  FROM [tbltest] where  [PNAME]  like '%'+@name+'%'

--Query 2:
SELECT [PNAME]  FROM [tbltest] where  [PNAME]  like '%sara%'

suppose that there is a NoneClustered Index on [PNAME] column of [tbltest]. when running Queries, Excution plan show index Seek For Query 1 and Index Scan for Query 2. i expected that Excution Paln Show Index Scan For both queries,but because of using parameter in the first Query,it Show Index Seek. So what i the mater? in both query we used '%' at oth side,and know that in this state ,sql does not consider index but why in first Query Excution Plan Show Index Seek? thanks

like image 974
Mohammad Avatar asked Jul 30 '26 10:07

Mohammad


1 Answers

Query one uses a parameter, query 2 a constant.

The plan for query 2 will not be reused if you change the constant value.

The query for plan 1 can be. In this case, SQL Server (simply) leaves it's options open for reusing the plan.

AKA: the queries are not the same.

If you force parameterisation, then you should make both queries run like query 1. But I haven't tried...

like image 60
gbn Avatar answered Aug 02 '26 01:08

gbn



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!