Home > Articles > Data > SQL Server

Optimizing Views and Queries

Before getting into the details of optimizing views and queries, consider how SQL Server processes commands that are sent to it.

How SQL Server Processes Commands

When a command is sent to SQL Server for execution, SQL Server performs five steps to execute that command:

  1. The command is parsed.

  2. The Transact-SQL is standardized. Names are converted into codes that SQL Server can work with internally (such as table names being turned into object IDs, column names into column IDs, and so on).

  3. The query is optimized, and an execution plan is generated.

  4. The query is compiled.

  5. The query is executed.

When you create and save a view or a stored procedure, SQL Server goes through the first two steps only. However, there's a catch where views are concerned. Because you use views as though they were virtual tables, any command that uses a view (SELECT * FROM MyView) has to go through the first two steps a second time, so you really don't gain anything. Nevertheless, there's no real performance hit either, because once SQL Server gets through the first two steps on the command using the view, it can ignore the view itself. Then the command and the view go through optimization, compilation, and execution.

Any command sent to SQL Server benefits from the way SQL Server caches ad hoc statements. If the command is executed a second time in more or less the same form, SQL Server will reuse the cached plan. The performance advantage can be significant if you reuse the same view because the view portion is exactly the same each time.

This is where indexing becomes important—one of the things you can do to improve the performance of your queries, views, and stored procedures is to utilize efficient index design. The SQL Server query optimizer will automatically select the most efficient index for any given query, but that index has to exist in order for it to be used. To get optimal performance out of your queries, you need to create the necessary indexes. However, creating indexes incorrectly can cause worse performance problems than if you had no indexes, so the query optimizer might not use an index if using that index would result in a worse plan than it could achieve otherwise.

Indexing Guidelines

The following are some useful guidelines to observe when you're creating indexes:

  • Create indexes on columns that are used for searching or sorting. Index columns in WHERE and GROUP BY clauses that either return an exact match or have a high proportion of distinct values.

  • Don't create indexes on columns with few unique values. For example, do not create an index on the Country column if the only values it ever contains are the United States, Canada, and Mexico, even though you sort or search by country all the time.

  • Index columns used in joins. In Access, when you create a foreign key, Jet creates a hidden index on the column automatically. SQL Server does not do this, even if you have enforced Declarative Referential Integrity (DRI) by creating a foreign key. In SQL Server, you need to explicitly create indexes on any columns used in joins, unless the values are highly duplicated. Again, don't index Country even though it may be a foreign key if the data only contains a small number of distinct Country values.

  • You can't create indexes on columns defined with the text, ntext, image, or bit data types.

  • Let the Query Analyzer help you out, as discussed in the next section.

Using the Query Analyzer to Tune Performance

Whether your query is implemented in a view or in a stored procedure, using the Query Analyzer's tools can be a big help in optimizing it to run as quickly as possible.

Displaying the Plan

The Query Analyzer's options for helping you understand how a given query is going to execute are all on the Query menu, shown in Figure 9.11. You can display the estimated execution plan for the query, perform index analysis, show the execution plan when the query executes, show a server trace, and show client statistics.

Figure 9.11
Options available on the Query menu.

The Display Estimated Execution Plan Option

To display the estimated execution plan for a query, highlight the text of the query and press Ctrl+L or select Display Estimated Execution Plan from the Query menu. The execution plan is a graphical display of the data-retrieval methods the SQL Server query optimizer uses. Figure 9.12 shows the estimated execution plan for a query that totals the amount sold by an employee. The icons shown represent the execution of specific statements and queries. If you hover your mouse above each icon, a pop-up box appears listing the statistics for that specific statement. This can alert you to potential problems before you roll out your queries, as shown in Figure 9.12, which displays a warning box that statistics are missing for a table used in the query. The importance of updating statistics will be discussed later in this section.

Figure 9.12
Displaying the estimated execution plan for a query.

Displaying Index Analysis with the Index Tuning Wizard

In SQL Server 2000, choosing Display Index Analysis from the Query menu runs the Index Tuning Wizard, which analyzes the workload and the database and then recommends an index configuration that will improve the performance of the workload. The introductory dialog box the Index Tuning Wizard displays after launching informs you that it can perform the following tasks:

  • Identify the server and databases to tune

  • Identify the workload to analyze

  • Select the tables to tune

  • Analyze the data and make index recommendations

  • Implement the index recommendations


Note - In SQL Server 7.0, the option in the Query Analyzer for performing index analysis simply analyzes the current query and displays its results and recommendations in the Messages pane. It will also offer to create any indexes it thinks might help.


The next dialog box lets you select a database to work with. If you don't want to analyze all the tables, you can select or deselect them later, but the wizard will only work with one database at a time. There are three additional options, as shown in Figure 9.13. You can elect to keep or drop all existing indexes, perform a thorough analysis, and add indexed views, which are covered earlier in this chapter.

Figure 9.13
Selecting the database to tune and setting options for the Index Tuning Wizard.

The next wizard dialog box allows you to select a workload from the following three options:

  • My workload file, which is a workload file previously generated with the SQL Server Profiler (see Chapter 15, "Deployment, Tuning, and Maintenance," for information on the SQL Server Profiler).

  • SQL Server table.

  • Query Analyzer selection, which is the default if you launch the Index Tuning Wizard from the Query Analyzer.

You can also use the Advanced Options tab to limit the number of queries that are sampled, to set a limit on the space used for any recommended indexes, and to limit the maximum number of columns per index.

The next wizard dialog box allows you to select the tables to tune, as shown in Figure 9.14.

Figure 9.14
Selecting the tables to tune.

The following dialog box in the wizard displays recommendations, if any. Running the Index Tuning Wizard on the Northwind database is not very productive because the indexes are already in place.

You can then elect to implement the recommendations on the final wizard dialog box, as shown in Figure 9.15.

Figure 9.15
Applying the recommended changes.

The final wizard dialog box displays the following information:

  • If you chose to execute now, the database will be updated to the recommended configuration.

  • If you chose to schedule a job, you can view the job in the SQL Server Enterprise Manager.

  • If you chose to save the script to a file, you can view or edit the script with a text editor. (It doesn't say so, but you can also use the Query Analyzer or the Profiler for this editing job.)

The wizard then gives you a piece of good advice: You should back up your database before implementing the recommended configuration. Once you click Finish, the job will be processed (or not, depending on the options you've chosen).

The Show Execution Plan Option

The Show Execution Plan (Ctrl+K) option is different from the Display Estimated Execution Plan option discussed earlier. This option can be toggled on or off. When it's turned on, an additional tab is added to the results pane that displays the execution plan for the query, as shown in Figure 9.16. You won't see anything before the query is executed.

Figure 9.16
Show Execution Plan adds two tabs to the results pane for the execution plan and the statistics.

The Show Server Trace Option

The Show Server Trace option, which is new in SQL Server 2000, also adds an additional tab to the results pane to display the trace results, as shown in Figure 9.17. A server trace provides information about the event class, subclass, integer data, text data, database ID, duration, start time, reads and writes, and CPU usage.

Figure 9.17
Displaying server trace information for a query.

In earlier versions, you had to use the Profiler to see this information. Now it is available right in Query Analyzer.

The Show Client Statistics Option

The Show Client Statistics option is also new in SQL Server 2000. It adds one more tab to the results pane to display statistics, as shown in Figure 9.18.

Figure 9.18
Displaying client statistics.

Statistics and Indexes

Statistics are very important to the query optimizer—if it does not have good statistical information, it can't make useful recommendations or process queries efficiently. All indexes have distribution statistics that describe the selectivity and distribution of the key values in the index. The selectivity of an index relates to how many rows are identified by each key value. For example, a unique key has high selectivity, whereas a key that is found in many rows has poor selectivity. Fields with a small set of values, like gender for employees, benefit little from indexes, because those indexes will have poor selectivity and will therefore usually be ignored by the optimizer. Distribution statistics measure how the values are spread out among your records. You might have customers in 50 different countries, but if 90% of your customers are in one country, then country isn't a very useful index. The selectivity and distribution statistics are used by SQL Server when processing Transact-SQL statements and are crucial for estimating how efficient an index would be when retrieving data associated with a key value or a range specified in the query. The query optimizer can even compile and use statistics on non-indexed fields. It's very important that your statistics be updated if the composition of your data changes significantly. You can set statistics to be created and updated automatically by going into the Options tab in the Database Properties dialog box, as shown in Figure 9.19.

Figure 9.19
Setting Auto Create Statistics and Auto Update Statistics in the database's Properties dialog box.

Updating Statistics (New)

You can update statistics in the Query Analyzer by choosing Tools, Manage Statistics from the menu bar. This will bring up the dialog box shown in Figure 9.20.

Figure 9.20
The Manage Statistics dialog box lets you update statistics.

Click the New button to create statistics for columns not listed. This will bring up the dialog box where you can create additional statistics, as shown in Figure 9.21.

Figure 9.21
Creating missing statistics.

Managing Indexes

A new feature in SQL Server 2000 is the way you can use the Query Analyzer to manage indexes without having to use the Enterprise Manager or another tool. Choose Tools, Manage Indexes from the menu bar. This will load the dialog box shown in Figure 9.22. You can create a new index or edit an existing one.

Figure 9.22
The Manage Indexes dialog box lets you add a new index or edit an existing one.

If you choose the Edit option, you'll get the Edit Existing Index dialog box, as shown in Figure 9.23.

Figure 9.23
Editing an existing index.

As you can see, the Query Analyzer offers a powerful set of tools for tuning and optimizing your queries. Performance tuning is also covered in Chapter 15.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020