Wednesday, April 5, 2023

Profile name is not valid - SQL-Serer Database Mail

Problem

When trying to send emails from SQL Server using using the sp_send_dbmail stored procedure the following error can appear (on SQL Server 2005 or 2008):
  1. EXECUTE msdb.dbo.sp_send_dbmail
  2. @profile_name = 'PROFILE_NAME', -- Change This
  3. @recipients = 'recipient@domain.com', -- Change This
  4. @Subject = 'Test Message generated from SQL Server DatabaseMail',
  5. @Body = 'This is a test message from SQL Server DatabaseMail'

Msg 14607, Level 16, State 1, Procedure sp_send_dbmail, Line 141
profile name is not valid

The Database Mail feature is installed and configured (the Database Mail feature is enabled and the necessary account and profile is created). As sysadmin the emails are send successfully using sp_send_dbmail stored procedure.
The problem appear when trying to call the sp_send_dbmail stored procedure as a non-sysadmin login. Also the executing non-syadmin login has been added to DatabaseMailUserRole role in msdb database.


Cause
This happens because there the database mail profile is not set with public access and the login is not allowed to use the specified profile.

 
Solution:
1. Set the profile used as Public
Right click on the Database Mail in Management Studio and select the Configure Database Mail menu option.


Choose Manage profile security

Go to Public Profiles, select your profile name and then set the profile as Public.

OR
2. Go to Private Profiles and grant rights to use the specified profile to the login that executes the sp_send_dbmail stored procedure.

SQL SERVER - 2008 - Configure Database Mail - Send Email From SQL Database

In this article, I discuss about the Database Mail which is used to send the email using SQL Server. Previously I had discussed about SQL SERVER - Difference Between Database Mail and SQLMail. Database mail is the replacement for SQLMail with many enhancements. So one should stop using SQLMail and upgrade to the Database Mail.
In order to send mail using Database Mail in SQL Server, there are 3 basic steps that need to be carried out:
  1. Create Profile and Account
  2. Configure Email
  3. Send Email

Step 1: Create Profile and Account

You need to create a profile and account using the Configure Database Mail Wizard which can be accessed from the Configure Database Mail context menu of the Database Mail node in Management Node.
This wizard is used to manage accounts, profiles, and Database Mail global settings which are shown below:











Step 2: Configure Email

After the Account and the Profile are created successfully, we need to configure the Database Mail. To configure it, we need to enable the Database Mail XPs parameter through the sp_configure stored procedure, as shown here:
sp_CONFIGURE 'show advanced', 1 GO RECONFIGURE GO sp_CONFIGURE _
 'Database Mail XPs', 1 GO RECONFIGURE GO 

Step 3: Send Email

After all configurations are done, we are now ready to send an email. To send mail, we need to execute a stored procedure sp_send_dbmail and provide the required parameters as shown below:
USE msdb GO EXEC sp_send_dbmail @profile_name='PinalProfile', _
@recipients='test@Example.com', @subject='Test message', _
@body='This is the body of the test message. _
Congrats Database Mail Received By you Successfully.' 

After all validations of the parameters entered are done, certain stored procedures are executed and the mail is queued by Service Broker. Read more at SQL SERVER - Introduction to Service Broker.
Database Mail keeps copies of outgoing e-mail messages and displays them in the sysmail_allitems, sysmail_sentitems, sysmail_unsentitems, sysmail_faileditems. The status of the mail sent can be seen in sysmail_mailitems table. When the mail is sent successfully, the sent_status field of the sysmail_mailitems table is set to 1 which can again be seen in sysmail_sentitems table. The mails that have failed will have the sent_status field value to 2 and those are unsent will have value 3. The log can be checked in sysmail_log table as shown below:
SELECT * FROM sysmail_mailitems GO SELECT * FROM sysmail_log GO 

Status can be verified using sysmail_sentitems table.

After sending mail, you can check the mail received in your inbox, just as I received as shown below:

 

Estimated Execution Plan

Indexes directly affect the performance of database applications. This article uses analogies to describe how indexes work. The estimated execution plan feature of the Query Window is utilized to compare the performance of two queries in a batch.


Most developers and DBAs understand that indexes on database tables enable applications and reports to run more efficiently. But, do they really know whether the database system will take advantage of an index to process a particular query or update statement? Does the order of columns specified in the index matter? What is the difference between a clustered index and a non-clustered index? To understand some index concepts, I have found it useful to use some analogies.
To follow along with this article, you will need an instance of SQL Server 2005 with the AdventureWorks database installed. Each example will compare the performance of two queries in the same batch using the Graphical Estimated Execution Plan. We will focus on the "Query Cost (relative to the batch)" to compare the performance of the two queries. To see the Graphical Estimated Execution Plan, click the button shown below (Figure 1) instead of running the query.
Figure 1
Figure 1: The button for the Estimated Execution Plan

Clustered Indexes

A printed phone directory is a great example of a clustered index. Each entry in the directory represents one row of the table. A table can have only one clustered index. That is because a clustered index is the actual table sorted in order of the cluster key. At first glance, you might think that inserting a new row into the table will require all the rows after the inserted row to be moved on the disk. Luckily, this is not the case. The row will have to be inserted into the correct data page, and this might require a page split if there is not enough room on the page for the new row. A list of pointers maintains the order between the pages, so the rows in other pages will not have to actually move.
The primary key of the phone directory is the phone number. Usually the primary key is used as the clustering key as well, but this is not the case in our example. The cluster key in the phone directory is a combination of last name and first name. How would you find a friend's phone number if you knew the last and first name? Easy, open the book approximately to the section of the book that contains the entry. If your friend's last name starts with an "F", you will search near the beginning of the book, if an "S", you will search towards the back. You can use the names printed at the top of the page to quickly locate the page with the listing. You then drill down to the section of the correct page till you find the last name you are looking for. Now you can use the first name to choose the correct listing. The phone number is right there next to the name. It probably takes more time describe the process than to actually do it. Using the last name plus first name to find the number is called a clustered index seek.
Lets say you wanted to find all the people who have the last name of "Smith" for a family reunion. How quickly could you locate all the names? Of course, it would take a matter of seconds to find all of them grouped together, possibly over a few pages. What if you wanted to locate everyone with the first name of "Jeff" in the book? Could it be done? Of course it could, but you would have to look at every entry in the entire book because the first name is the second column in our cluster key. This is called a clustered index scan, a very expensive operation on a big table.
Here is an example using one of the tables in AdventureWorks. The Sales.SalesOrderDetail table has a clustered index on SalesOrderID plus SalesOrderDetailID. Take a look at the graphical estimated execution plan (Figure 2) of the batch paying particular attention to the Query cost when either the first or second column in the cluster key is used.
SELECT SalesOrderID, SalesOrderDetailID
FROM Sales.SalesOrderDetail
WHERE SalesOrderID = 58950

SELECT SalesOrderID, SalesOrderDetailID
FROM Sales.SalesOrderDetail
WHERE SalesOrderDetailID = 68531
Figure 2
Figure 2: Compare the query costs when either the first or second column is searched.
The first query in the batch will utilize a "Clustered Index Seek" while the second will use a "Clustered Index Scan". Notice that the first query will use 1% of the cost of the batch while the second query will use 99% of the cost. These results make sense when you think about the fact that the first column of the index is SalesOrderID. When trying to find a particular row based on the SalesOrderDetailID in the second query, the entire table is searched.
Another search you probably wouldn't attempt with the phone directory is looking for every entry with a particular last name or a particular first name. If you wanted to find all of the entries with the first name of "Jeff" or the last name of "Smith" you would have to search every name in the book. Here is a batch illustrating this point:
SELECT SalesOrderID, SalesOrderDetailID
FROM Sales.SalesOrderDetail
WHERE SalesOrderID = 43683
   AND SalesOrderDetailID = 240

SELECT SalesOrderID, SalesOrderDetailID
FROM Sales.SalesOrderDetail
WHERE SalesOrderID = 43683
    OR SalesOrderDetailID = 240

Figure 3
Figure 3: Using "OR" causes a scan.
The second query using "OR" in the WHERE clause uses 99% of the resources of the batch because the entire clustered index must be scanned.

Non-Clustered Indexes

The index in the back of a book is an example of a non-clustered index. A non-clustered index has the indexed columns and a pointer or bookmark pointing to the actual row. In the case of our example it contains a page number. Another example could be a search done on Google or another of the search engines. The results on the page contain links to the original web pages. The thing to remember about non-clustered indexes is that you may have to retrieve part of the required information from the rows in the table. When using a book index, you will probably have to turn to the page of the book. When searching on Google, you will probably have to click the link to view the original page. If all of the information you need is included in the index, you have no need to visit the actual data.
In SQL Server 2000 the term "Bookmark Lookup" was used to describe the process of retrieving some of the columns from the actual row. In my experience, this is a very expensive operation when performed on large tables. Now "Clustered Index Seek" for tables with a clustered index, and "RID Lookup" for tables without a clustered index are the terms used. I find this very confusing since "Clustered Index Seek" is usually the preferred behavior. In Books Online, it states that when the keyword "LOOKUP" appears, it is actually a bookmark lookup. I haven't found the term displayed in the Graphical Execution plan. To see the keyword, you have to use the SHOWPLAN_TEXT option.
Here is a batch and the graphical execution plan (Figure 4) when using the non-clustered index to search on the ProductID column. The second query retrieves a column that is not included in the index key:
SELECT ProductID, SalesOrderID, SalesOrderDetailID
FROM Sales.SalesOrderDetail
WHERE ProductID = 776

SELECT CarrierTrackingNumber, ProductID
FROM Sales.SalesOrderDetail
WHERE ProductID = 776

Figure 4
Figure 4: Retrieving a column not part of the index.
The first query cost is 0% of the batch. In this case the ProductID is retrieved from the index -- no need to look at the actual table. The SalesOrderID and SalesOrderDetailID are not defined in the index, but are automatically included since they comprise the primary key. The second query in the batch costs 100% of the resources. Even though we are searching on an indexed column, we must retrieve the CarrierTrackingNumber from the actual table. Surprisingly, a "Clustered Index Seek" is the most expensive part of the query. To see why, run the following:
SET SHOWPLAN_TEXT ON
GO
SELECT CarrierTrackingNumber, ProductID
FROM Sales.SalesOrderDetail
WHERE ProductID = 776

Instead of executing the query, the execution plan is returned in text format (results abbreviated). The "LOOKUP" keyword designates that a bookmark lookup was used.
       |--Clustered Index Seek
       ...
        LOOKUP ORDERED FORWARD)

In the previous example, if the CarrierTrackingNumber was part of the index, the performance issue would be solved. Run this script to modify the index:
USE [AdventureWorks]
GO
DROP INDEX [IX_SalesOrderDetail_ProductID] ON [Sales].[SalesOrderDetail] WITH ( ONLINE = OFF )
GO
USE [AdventureWorks]
GO
CREATE NONCLUSTERED INDEX [IX_SalesOrderDetail_ProductID] ON [Sales].[SalesOrderDetail]
(
 [ProductID] ASC,
 [CarrierTrackingNumber] ASC
)

Now when the query batch is run, the second query has the same cost as the first query because the CarrierTrackingNumber is now part of the index. The table doesn't have to be accessed. Below is the graphical execution plan (Figure 5):
Figure 5
Figure 5: Using a covering index
When all of the required columns are part of the index, it is called a "covering index". An index key can contain up to 16 columns and can be up to 900 bytes wide. SQL Server 2005 has a new feature to create indexes that surpass these limits called "included columns". This allows you to include additional columns in the index over the 16 column limit or columns that would be too large to include.
While you can only have one clustered index per table, you can have up to 249 non-clustered indexes per table. If you ever have that many, rest assured, you have a design problem! An important thing to keep in mind is that while indexes can improve the performance of queries, indexes take up disk space and require resources to keep updated. If a table has four non-clustered indexes, every write to that table requires four additional writes to keep the indexes up to date.
One more interesting thing about non-clustered indexes is that SQL Server can use them in combination or along with the clustered index. The SalesOrderDetail table has a non-clustered index on the ModifiedDate column. This query batch shows the difference when a WHERE clause has two conditions. In the first query, there is no index on the second column used in the WHERE clause. In the second query, there is a separate index on each index in the WHERE clause. In this case, the SQL Server uses the two indexes in combination to process the query, and the performance of the second query is much better (Figure 6).
SELECT SalesOrderID
FROM Sales.SalesOrderDetail
WHERE ProductID = 804 and UnitPrice = 25

SELECT SalesOrderID
FROM Sales.SalesOrderDetail
WHERE ProductID = 804 and ModifiedDate = '6/1/2003'


Figure 6
Figure 6: Using two indexes in combination.
Recall how using the "OR" operator with a clustered index caused a clustered index scan. If there are individual indexes defined on two columns used in a WHERE clause with "OR", the performance is about the same as when "AND" is used. Here is an example comparing "AND" and "OR", and the costs are almost evenly divided (Figure 7):
SELECT SalesOrderID
FROM Sales.SalesOrderDetail
WHERE ProductID = 804 OR ModifiedDate = '6/1/2003'

SELECT SalesOrderID
FROM Sales.SalesOrderDetail
WHERE ProductID = 804 AND ModifiedDate = '6/1/2003'


Figure 7
Figure 7: Using "OR" with two indexes.
There are two more issues to consider concerning indexes and WHERE clauses. What happens when a function is used in the WHERE clause? In that case, the index will not be used because the function will have to be applied to every row in the table. What happens when a wildcard is used in the WHERE clause? In this case it depends on where the wildcard is located. If the first character of the search term is replaced with a wildcard, the index will not be used and a table scan will result. Think about our phone directory example for a minute. How easy would it be to find an entry if you did not know the first letter of the last name?

Conclusion

Strategically placed indexes can make a huge difference in the performance of an application, especially over time as the amount of data increases. It is important to remember that a clustered index is comprised of the actual rows sorted in order of the cluster key. A non-clustered index is comprised of the key columns plus a pointer to the actual rows. You can use the Estimated Execution Plan as a way to experiment. It allows you to compare two or more similar queries to see where most of the resources will be used in the batch and, therefore, which query will perform better.
- See more at: http://www.sqlteam.com/article/sql-server-indexes-the-basics#sthash.LqPyt89x.dpuf

Thursday, November 4, 2021

What is Auto Growth ?

Auto Growth

What is Auto-growth?

· An auto-growth event is the process by which the SQL Server engine expands the size of a database file when it runs out of space. Each database has its own auto-growth setting – that is set by the default setting of the model database. Rarely do we use the model setting.

Why set up the auto-growth for each database?

· If you don’t set up the auto-growth setting for each database and be proactive in your duties, then each time an auto-growth event is performed, SQL Server holds up database processing while an auto-growth event occurs. And this can cause poor performance.

·  What is the purpose of auto-growth and it’s consequences of not setting up the auto-growth properly?

·  Each time the auto-growth event occurs, the server need to expand this space and place the space in the disk.  However, since the space allocated for the database may not be next to each other on the disk, the will cause your database file to become fragmented, thus poor performance.

· The initial settings for auto-growth are set to the default values when defining a new database. These defaults are established by using the auto-growth settings on the model database files. 

·  How can I avoid auto-growth events from occurring too many times?

·  Pre-Size your databases and size the auto-growth to an appropriate.

When an auto-growth event occurs SQL Server needs to find additional disk space in which the database can grow. Most likely this disk space will not be physically right next to the existing database space, but instead will be somewhere else on the disk. This causes your database file to be physically fragmented on the disk. The more auto-growth events you have the more physical fragmentation you will have. When your database is physically fragmented it takes longer for SQL Server to read that databases, because it has to move the disk head around to all the different fragmented pieces to read your database. To avoid the issues associated with auto-growth events you need to minimize the number of auto-growth events that occur.

SQL : 

select db_name(s.database_id), s.database_id, s.file_id, s.physical_name as file_name, s.size*8 as SizeKB, s.max_size, 

case s.is_percent_growth when 1 then convert(varchar(10), s.growth) + '%' else convert(varchar(10), s.growth*8) + 'kb' end as Growth

from sys.master_files s

where s.type = 0 --data only;


USE DATABASE_NAME GO

ALTER DATABASE <DATABASE_NAME> MODIFY FILE (NAME = 'FILENAME', SIZE = 1234, FILEGROWTH = 1234) GO

UI For Default Setting : 

RigthClick Model Database -> Properties -> Files -> Change initial size, growth size

UI For Current Database

Rightclick database -> Properties -> File -> Change initial size, growth size

 



Friday, December 18, 2015

Introduction to SQL Server Filtered Indexes

Nonclustered indexes overview

Indexes are a necessity for most tables of any substantial size. When indexes are strategically and purposefully created, they can provide efficient and precise data access by allowing the query optimizer to find the best and shortest route to a desired result set. This is accomplished by using a B-tree method of quickly locating the index’s pointer to the actual data values that the query is requesting.
The benefits of traditional indexes, however, come at a cost. Nonclustered indexes are created as structures that are distinct from the data that they organize – essentially, a nonclustered index is a copy (of sorts) of the table, storing data for every row of the table. Therefore, the more records in a table, the larger the index must be – increasing the overall data storage cost for the table. Also, index maintenance times are increased as each new index is added. Indexes must be reorganized at certain intervals to maintain accuracy. An index becomes inaccurate as data is changed - insert, update, delete, and merge operations all create a maintenance requirement.
Traditional nonclustered indexes target all data in a column – including NULL values – even if certain values are never searched for.
In light of all this, it’s not surprising that Microsoft has provided a special type of index that optimizes and enhances traditional nonclustered indexes: filtered indexes. Let’s look at what they are and how they are used.

Filtered nonclustered indexes

Filtered indexes for SQL Server were introduced in SQL Server 2008. Put simply, filtered indexes are nonclustered indexes that have the addition of a WHERE clause. Although the WHERE clause in a filtered index allows only simple predicates, it provides notable improvements over a traditional nonclustered index. This allows the index to target specific data values – only records with certain values will be added to the index – resulting in a much smaller, more accurate, and more efficient index.
The basic syntax for creating a filtered index is:
CREATE NONCLUSTERED INDEX <index name>
ON <table> (<columns>)
WHERE <criteria>;
GO
Let’s set up a basic filtered index on the Sales.SalesOrderDetail table in the AdventureWorks2012 sample database. Since it’s the largest table in the database (more than 121,000 records), it should give us the best opportunity to see the benefits of a filtered index. The query we will be using will look like this, initially:
--find SalesOrderDetailIDs with UnitPrice > $2000
SELECT SalesOrderDetailID, UnitPrice
FROM AdventureWorks2012.Sales.SalesOrderDetail
WHERE UnitPrice > 2000
GO
If we look at the current execution plan for this query, we see that there are no existing indexes that could be used for an index seek to locate the matching records efficiently, and that a clustered index scan was performed instead. An index seek operation happens when the query engine is able to use an appropriate index to find the exact location of the requested data, using the b-tree method. An index scan operation happens when every row of an index must be examined in order to find values in columns that the index does not cover. We see that for our query, the clustered index was scanned to locate rows that match the given criteria for the UnitPrice column:
Since the UnitPrice column does not have an index, the clustered index on the primary key (SalesOrderDetailID) had to be scanned. Since there is no ORDER BY clause in our query, the clustered index scan was essentially the same as a table scan. A clustered index is built on the physical leaf pages of a table, so a table with a clustered index will always show a clustered index scan rather than a table scan in an execution plan - even if the two have the same query cost.
To help us with our testing as we compare the impact of creating new indexes, I’ve created a copy of theAdventureWorks2012 database, called AdventureWorks2012b.
Before we create a filtered index, let’s create a traditional nonclustered index on the UnitPrice column of theAdventureWorks2012b database’s Sales.SalesOrderDetail table, and see how that improves our query. We’ll compare the performance of a nonclustered index against the performance of a filtered nonclustered index - the query engine suggests that a nonclustered index could improve the query by over 92%.
--add nonclustered index to UnitPrice column
CREATE NONCLUSTERED INDEX ncIX_SalesOrderDetail_UnitPrice
ON AdventureWorks2012b.Sales.SalesOrderDetail(UnitPrice)
GO
Now let’s compare the query execution for both tables, in one batch:
--find SalesOrderDetailIDs with UnitPrice > $2000 - no index
SELECT SalesOrderDetailID, UnitPrice
FROM AdventureWorks2012.Sales.SalesOrderDetail
WHERE UnitPrice > 2000
GO

--find SalesOrderDetailIDs with UnitPrice > $2000 - using nonclustered index
SELECT SalesOrderDetailID, UnitPrice
FROM AdventureWorks2012b.Sales.SalesOrderDetail
WHERE UnitPrice > 2000
GO
It’s obvious that the introduction of a simple nonclustered index did improve our query by more than 90%. Since nonclustered indexes refer to the primary key (if it exists) of a table, our query did not incur a key lookup. A key lookup is an expensive operation what occurs when a column is included in the SELECT list of a query, but is not covered by an index.
Now let’s add a filtered index to the original table (AdventureWorks2012). The filtered index will be identical to the nonclustered index, with the addition of a WHERE clause. Let’s allow the WHERE criteria to search for UnitPricevalues that are greater than $1000:
--add nonclustered filtered index to UnitPrice column
CREATE NONCLUSTERED INDEX fIX_SalesOrderDetail_UnitPrice
ON AdventureWorks2012.Sales.SalesOrderDetail(UnitPrice)
WHERE UnitPrice > 1000
GO
Now we’ll run our batch query execution again:
--find SalesOrderDetailIDs with UnitPrice > $2000 – now using nonclustered filtered index
SELECT SalesOrderDetailID, UnitPrice
FROM AdventureWorks2012.Sales.SalesOrderDetail
WHERE UnitPrice > 2000
GO

--find SalesOrderDetailIDs with UnitPrice > $2000 – using nonclustered  index
SELECT SalesOrderDetailID, UnitPrice
FROM AdventureWorks2012b.Sales.SalesOrderDetail
WHERE UnitPrice > 2000
GO
We have reduced our query cost by almost ½ - using a filtered index instead of a traditional nonclustered index.
Let’s take a look at the storage cost difference of using a filtered index. By running the sp_spaceused stored procedure, we can find the difference:
--get total index size for AdventureWorks2012 database
USE AdventureWorks2012
GO
EXECUTE sp_spaceused 'Sales.SalesOrderDetail'

--get total index size for AdventureWorks2012b database
USE AdventureWorks2012b
GO
EXECUTE sp_spaceused 'Sales.SalesOrderDetail'
The ‘index_size’ data was the same for both databases before we added any indexes. We see that by using a filtered index, we’ve saved a considerable storage percentage – about 25%. Of course, the storage savings results of implementing a filtered index will vary depending on the selectivity of the index’s data.

Selectivity

Selectivity could be defined as "the percentage of matching rows compared to total rows, regarding a given query’s criteria." A lower percentage indicates higher selectivity. This means that if there are very few rows that meet a query’s (or an index’s, in the case of a filtered index) WHERE criteria compared to the total number of rows, the index is considered very selective. For example, unique data would provide the most selective results, while a table that has the same value for every row would be considered least selective. So, if we were to broaden the search criteria of our filtered index like this:
--add nonclustered filtered index to UnitPrice column
CREATE NONCLUSTERED INDEX fIX_SalesOrderDetail_UnitPrice
ON AdventureWorks2012.Sales.SalesOrderDetail(UnitPrice)
WHERE UnitPrice > 500
GO
…the index size of the filtered index would be increased:

Sparse columns

Sparse columns are perfect candidates for filtered indexes. Sparse columns offer very efficient storage for columns that contain many NULL values – using no storage space whatsoever for the actual NULL data values. A sparse column must be nullable, and should be used for data where it is expected that the data will be mostly NULL values. A table that contains a sparse column can be created like this:
--create table with sparse column
CREATE TABLE Customers
(
ID INT PRIMARY KEY,
FName VARCHAR(20),
LName VARCHAR(20),
Email VARCHAR(100) SPARSE NULL
)
GO
A filtered index that would work well for the sparse Email column in this table might look like this:
--add nonclustered filtered index to sparse column
CREATE NONCLUSTERED INDEX fIX_Customers_Email
ON Customers(Email)
WHERE Email IS NOT NULL
GO
The index will ensure that query time is not wasted on the records with NULL email addresses.

Unique filtered indexes

Filtered indexes are a good solution in a situation where all column data must be unique - with the exception of NULL values. For example, if we want to make sure that all customers use a unique email address if they have one, but still allow the Email column to be NULL, we can use a UNIQUE filtered index:
--add  unique nonclustered filtered index that allows NULLs
CREATE UNIQUE NONCLUSTERED INDEX uq_fIX_Customers_Email
ON Customers(Email)
WHERE Email IS NOT NULL
GO
A traditional nonclustered UNIQUE index will allow only one NULL value. By using a filtered UNIQUE index, we allow multiple NULL Email records, while still guaranteeing that all other Email values will be unique.

Include clause

Filtered indexes offer the added benefit of an optional INCLUDE clause. Using an INCLUDE clause in a nonclustered index provides the ability to cover additional columns in a query’s SELECT list without needing to access a clustered index to access those columns. Therefore, the index can be utilized by wider queries without incurring additional key lookup costs. Let’s demonstrate the use of the INCLUDE clause. If we decide that we also want to return the UnitPriceDiscount field in our SalesOrderDetail query batch, neither of our indexes would be utilized:
--find SalesOrderDetailIDs with UnitPrice > $2000 – using filtered index with additional column
SELECT SalesOrderDetailID, UnitPrice, UnitPriceDiscount
FROM AdventureWorks2012.Sales.SalesOrderDetail
WHERE UnitPrice > 2000
GO

--find SalesOrderDetailIDs with UnitPrice > $2000 – using nonclustered index with additional column
SELECT SalesOrderDetailID, UnitPrice, UnitPriceDiscount
FROM AdventureWorks2012b.Sales.SalesOrderDetail
WHERE UnitPrice > 2000
GO
The addition of the UnitPriceDiscount column in the select list has caused our nonclustered indexes to be ignored. However, if we add an INCLUDE clause to each index, we can return to similar query cost results:
--drop filtered index
DROP INDEX fIX_SalesOrderDetail_UnitPrice
ON AdventureWorks2012.Sales.SalesOrderDetail
GO

--drop nonclustered index
DROP INDEX ncIX_SalesOrderDetail_UnitPrice
ON AdventureWorks2012b.Sales.SalesOrderDetail
GO

--re-add filtered index to UnitPrice column, include UnitPriceDiscount column
CREATE NONCLUSTERED INDEX fIX_SalesOrderDetail_UnitPrice
ON AdventureWorks2012.Sales.SalesOrderDetail(UnitPrice)
INCLUDE (UnitPriceDiscount)
WHERE UnitPrice > 1000
GO

-- re-add nonclustered index to UnitPrice column, include UnitPriceDiscount column
CREATE NONCLUSTERED INDEX ncIX_SalesOrderDetail_UnitPrice
ON AdventureWorks2012b.Sales.SalesOrderDetail(UnitPrice)
INCLUDE (UnitPriceDiscount)
GO

--find SalesOrderDetailIDs with UnitPrice > $2000 – using filtered index, now with additional column
SELECT SalesOrderDetailID, UnitPrice, UnitPriceDiscount
FROM AdventureWorks2012.Sales.SalesOrderDetail
WHERE UnitPrice > 2000
GO

--find SalesOrderDetailIDs with UnitPrice > $2000 – using nonclustered index, now with additional column
SELECT SalesOrderDetailID, UnitPrice, UnitPriceDiscount
FROM AdventureWorks2012b.Sales.SalesOrderDetail
WHERE UnitPrice > 2000
GO
We’ve expanded the capabilities of our index to cover the UnitPriceDiscount column. Our query that containsUnitPriceDiscount in the SELECT list is now optimized.

Advantages of using filtered indexes

Some key benefits of using filtered indexes are:
  • Reduced index maintenance costs. Insert, update, delete, and merge operations are not as expensive, since a filtered index is smaller and does not require as much time for reorganization or rebuilding.
  • Reduced storage cost. The smaller size of a filtered index results in a lower overall index storage requirement.
  • More accurate statistics. Filtered index statistics cover only the rows the meet the WHERE criteria, so in general, they are more accurate than full-table statistics.
  • Optimized query performance. Because filtered indexes are smaller and have more accurate statistics, queries and execution plans are more efficient.

Limitations

Some limitations on using filtered indexes are:
  • Statistics may not get updated often enough, depending on how often filtered column data is changed. Because of how SQL Server decides when to update statistics (when about 20% of a column’s data has been modified), statistics could become quite out of date. The solution to this issue is to set up a job to run UPDATE STATISTICS more frequently.
  • Filtered indexes cannot be created on views. However, a filtered index on the base table of a view will still optimize a view’s query.
  • XML indexes and full-text indexes cannot be filtered. Only nonclustered indexes are able to take advantage of the WHERE clause.
  • The WHERE clause of a filtered index will accept simple predicates only. For example,
    --add nonclustered filtered index to ModifiedDate column
    CREATE NONCLUSTERED INDEX fIX_SalesOrderDetail_ModifiedDate
    ON AdventureWorks2012.Sales.SalesOrderDetail(ModifiedDate)
    WHERE ModifiedDate BETWEEN '2008-01-01' AND '2008-01-07'
    GO
    …results in an error:
    ..but this:
    --add nonclustered filtered index to ModifiedDate column
    CREATE NONCLUSTERED INDEX fIX_SalesOrderDetail_ModifiedDate
    ON AdventureWorks2012.Sales.SalesOrderDetail(ModifiedDate)
    WHERE ModifiedDate >= '2008-01-01'  <= '2008-01-07'
    GO
    …is accepted. Using date functions also results in an error:
    --add nonclustered filtered index to ModifiedDate column
    CREATE NONCLUSTERED INDEX fIX_SalesOrderDetail_ModifiedDate
    ON AdventureWorks2012.Sales.SalesOrderDetail(ModifiedDate)
    WHERE ModifiedDate  = GETDATE() 
    GO
    Computed, spatial, and UDT columns are also not allowed as comparison criteria. The IN clause is allowed.

How to know when a filtered index is needed

There are obvious benefits to using filtered indexes, but how can we know if certain queries are used often enough to warrant a filtered index? One way to know this is to be intimately aware of the exact queries that are used – by using SQL Profiler to capture query text, or by examining often-used stored procedures and application code. Another method is to use the Database Tuning Advisor. The Database Tuning Advisor offers missing index suggestions, based on a workload file or table. The workload is normally the results of a SQL Server Profiler trace that is consumed and examined. The Tuning Advisor evaluates what queries are executed and how often, and decides if a database table might benefit from additional indexes. The Advisor can be started from Management Studio by selecting Database Tuning Advisor from the Tools menu. Then, in the Tuning Options tab, there is a checkbox labeled ‘Include filtered indexes’ – when this is checked, the Advisor will recommend filtered indexes, where beneficial.

Conclusion

Filtered indexes offer great benefits in terms of query execution performance and index storage savings. Because traditional nonclustered indexes are so necessary, but can rack up high maintenance and storage costs, the filtered index optimization should be considered wherever possible. However, care should be taken not to eliminate any current nonclustered indexes that cannot easily be replaced with filtered indexes.

We recently have seen some issue’s with the use of filtered indexes. While this added feature is not widely used, we would like to caution people when using them.
The problem has to do with the “quoted_identifier” setting that becomes a part of the index itself and how that interacts with certain connection types.
One of the results of this bug is that data fixes issued against tables with filtered indexes will fail unless the “SET QUOTED_IDENTIFIER ON” statement is explicitly made part of the data fix. So if you are aware of a table with a filtered index, and you have a data fix for that table, please include the “SET QUOTED_IDENTIFIER ON” setting.