[Solved] Does parameter sniffing exist for views?

EverSQL Database Performance Knowledge Base

Does parameter sniffing exist for views?

I've heard of and encountered parameter sniffing in stored procedures before. But today I ran into the first instance of what I can only assume is parameter sniffing in a view.

I have a query that selects from a number of tables and a view. It's basically:

select *
from view v
inner join table t
on v.id = t.id
where v.date = @EndDate;

With the parameter in place, the query will attempt to execute literally for hours. I've let it sit for over 2 hours and nothing gets returned. If I replace the parameter with a specific date where v.date = '2017-11-20' or even a calculated value where v.date = cast(getdate() as date) it will return in 2 seconds. I can keep the parameter in by adding option (recompile) to the end of the query and it will return results in a second or two.

So I know how to fix this, I am really just asking: Is this something that others have run into before? Is it possible it's not parameter sniffing but rather something else?


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. Avoid Selecting Unnecessary Columns (query line: 2): Avoid selecting all columns with the '*' wildcard, unless you intend to use them all. Selecting redundant columns may result in unnecessary performance degradation.
  2. 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 `table` ADD INDEX `table_idx_id` (`id`);
ALTER TABLE `view` ADD INDEX `view_idx_date` (`date`);
The optimized query:
        view v 
        table t 
            ON v.id = t.id 
        v.date = @EndDate

Related Articles

* original question posted on StackOverflow here.