[Solved] Getting strange reaction in T-SQL script
Looking to automatically optimize YOUR SQL query? Start for free.

EverSQL Database Performance Knowledge Base

Getting strange reaction in T-SQL script

I am writing a stored procedure and when I tested the procedure in Execution Plan/Sentry Plan Explorer I have noticed that in one statement the plan reacts strangely.

Here are 2 scripts that from my point of view are the same, but the results are significantly different.

Script 1 (not real code, but a code that demonstrates the problem):

DECLARE @MyVariable INT;
SET @MyVariable = 123456789;

SELECT MT.Name, OT.Name
FROM MyTable MT
INNER JOIN OtherTable OT ON MT.ID = OT.MyTableID
WHERE OT.TypeID = @MyVariable;

Script 2:

SELECT MT.Name, OT.Name
FROM MyTable MT
INNER JOIN OtherTable OT ON MT.ID = OT.MyTableID
WHERE OT.TypeID = 123456789;

It seems to be the same, but the results I get are different:

  1. Estimated rows in Script 1: 15621 rows (wrong for sure, too many rows)
  2. Estimated rows in Script 2: 205 rows (logical result, probably true)

I think that the SQL execution plan behaves differently when a variable is used in the where clause. Why? Or what is going on here? How to improve this?

Thanks

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
Optimal indexes for this query:
ALTER TABLE `MyTable` ADD INDEX `mytable_idx_id` (`ID`);
ALTER TABLE `OtherTable` ADD INDEX `othertable_idx_typeid` (`TypeID`);
The optimized query:
SELECT
        MT.Name,
        OT.Name 
    FROM
        MyTable MT 
    INNER JOIN
        OtherTable OT 
            ON MT.ID = OT.MyTableID 
    WHERE
        OT.TypeID = 123456789

Related Articles



* original question posted on StackOverflow here.