Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. SQL Server
  3. Question
SQL Server

How to Create a Query using a filtered index but wrong estimated number of rows?

Asked by Aalap Prabhakaran Jul 19, 2021 859 views 1 answer
Share

About this question

 I have a table with a nonclustered index on a datetime2 field. On that same table I have a field (char[1]) which is used to logically delete records and can have 2 distinct values : A(active) or D(deleted).

There are 451047 records with the datetime2 field set at NULL but only 7095 are marked as A. Every query in the application looks for active records only, so, every query that's looking for NULLs in the datetime field was getting really bad estimates and, with that, bad execution plans.

Simple example: Plan without filtered index: look at estimated rows vs actual rows

I decided then to create a filtered non clustered index but estimates were still incorrect: Plan using a filtered index, still getting wrong estimates

It looks like I still get the old estimates, even if the query is using the filtered index. Does anyone know the reason for this behaviour?

These are the new statistics of the filtered index: Filtered index statistics Table definition:

CREATE TABLE [TYDATPRD].[HAND00F]( [STDRECSTS] [char](1) NULL, [HDHAND] [numeric](14, 0) IDENTITY(1,1) NOT NULL, [HDCHKINDT] [datetime2](7) NULL, --lots of other columns which I don't think are needed CONSTRAINT [PK_TYDATPRD_HAND00F] PRIMARY KEY CLUSTERED ( [HDHAND] ASC ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [DATA] ) ON [DATA]
Nonclustered filtered index definition:
CREATE NONCLUSTERED INDEX [IX_HAND00F_HDCHKINDT] ON [TYDATPRD].[HAND00F] ( [HDCHKINDT] ASC ) WHERE [STDRECSTS]='A' WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [INDEXES] GO

Your answer

1 Answer

More SQL Server discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest SQL Server Blogs

Guides, tips and career advice on SQL Server from JanBask experts.