Why am I getting cardinality issues when querying a single table
-
11-12-2020 - |
Question
I have the following query:
SELECT
[iri].[RateItemKey],
[iri].[RateItemType]
FROM
[prism72].[dbo].[ispRateItem] AS [iri]
WHERE
[iri].[Status] = 1
AND (
[iri].[RateItemType] IN (3,2)
)
The ispRateItem table has the following indexes:
CREATE NONCLUSTERED INDEX [COVIX_ispRateItem_RateItemType_Status] ON [dbo].[ispRateItem]
(
[Status] ASC,
[RateItemType] ASC
)
INCLUDE ( [RateItemKey]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
CREATE UNIQUE CLUSTERED INDEX [CLIX_ispRateItem] ON [dbo].[ispRateItem]
(
[RateItemKey] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
ALTER TABLE [dbo].[ispRateItem] ADD CONSTRAINT [RateItem_PK] PRIMARY KEY NONCLUSTERED
(
[RateItemKey] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 90) ON [PRIMARY]
GO
I've updated the statistics using:
UPDATE STATISTICS [ispRateItem] WITH FULLSCAN, ALL;
However I index the table I get the same cardinality issue: Est Rows 1565, Actual Rows 4315. I've even tried removing all indexes (resulting in a table scan).
What could be causing this?
Please note that I'm a beginner to query tuning.
Thanks.
Alan
Solution
I think your problem is the fact your WHERE
clause has multiple predicates on the same table. This article by Paul White explains the issue.
It may be possible to get around this issue by having a computed column
that does what your current WHERE
clause does. You could then use this column on it's own but this would need a bit of testing to make sure it works OK.
The resolution:
James suggestion got me looking into multiple predicate issues. So I tested using single predicates and noticed that integers were being stored as varchar for the RateItemType field.
The problem was resolved by making the following change:
[iri].[RateItemType] IN (3,2)
to
[iri].[RateItemType] IN ('3','2')