Live classes start in 1d 00h 40m — Save your seat

Performance Tuning

When You Need to Tune A View, Don’t Just Get Its Plan

Say your database has a view, and everybody’s queries use it. Let’s take the Stack Overflow database and create this view:

Not pretty, but that’s why you’re here, right? Real world code is ugly.

And say my users are running queries like these:

Notice that the select, where, order by etc all have variations in them. They’re not all asking for the same fields, which means SQL Server can make different decisions about:

  • Which tables in the joins are necessary
  • Which indexes should be used on each table
  • How much memory to allocate to each query

As a result, the execution plans all look totally different:

Totally different query plans

The thing those queries all have in common is the view, so sometimes folks say, “I need help tuning this view.” They run:

They get the execution plan, post it at DBA.StackExchange.com, and everybody tells them how terrible that view is. Thing is, that doesn’t really prove anything – because SQL Server uses the view in different ways. It’s just a starting point for the query’s execution plan.

When you need to tune a query that hits a view, don’t just investigate the view’s plan. Investigate your slow query’s plan, and you’ll get much more useful and targeted advice.

Free, 3× a week

Get my new posts by email

Three posts a week, plus a Monday roundup of the best database news from around the web.

2 comments

  1. Yep… same thing for inline table valued functions as well, the plans need to be analyzed as a part of how they are called.

  2. Yup, after all there’s no such thing as a “tuning a view” or a “view’s plan”. We gotta tune the queries and their plans.

Leave a comment

Email me: