Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the parameterized version of this query run slower than a non-parameterized version?

Sample Query:

CREATE PROCEDURE dbo.Test (@p varchar(10))
AS
DECLARE @param varchar(10)
SET @param = @p + '%'

SELECT * FROM table1 t1
INNER JOIN table2 t2 on t1.id = tr.id
WHERE t2.desc LIKE @param

I've a query which is similar to one above and when i use this in stored procedure it runs indefinitely without giving any output. But if i use same query as,

SELECT * FROM table1 t1
INNER JOIN table2 t2 on t1.id = tr.id
WHERE t2.desc LIKE 'A%'  -- notice no parameter here

This executes in less than a second.

My table2 has 140K records and table1 some 250K

Any idea what could be causing like operator to run slow?

like image 811
rs. Avatar asked Oct 19 '10 16:10

rs.


People also ask

Are parameterized queries faster?

"parameterized queries typically execute much faster than a literal SQL string because they are parsed exactly once (rather than each time the SQL string is assigned to the CommandText property)."

What are some advantages of parameterized queries?

The main advantage of a parameterized query is that the query does not need to be prepared each time it is run. A good example of this is scrolling a master record while the detail is refreshed based on the new record.

Why is it important to parameterized database queries?

The benefit of parameterized SQL queries is that you can prepare them ahead of time and reuse them for similar applications without having to create distinct SQL queries for each case.

What is difference between parameterized query and stored procedure?

Short answer is, parameterized queries function the same way as stored procedures. SQL Server will be able to reuse execution plans because it will recognized the parameters as such. So from the performance point of view, there's no real difference.


1 Answers

It does not know at compile time that @param will not have a leading wildcard so when it compiles the batch it gives you a plan with a scan not a seek.

You could maybe try OPTION (RECOMPILE) or OPTION (FORCESEEK) (SQL Server 2008) to see if it gives you a better plan.

like image 147
Martin Smith Avatar answered Oct 04 '22 02:10

Martin Smith