Given I am using the AdventureWorks2016 OLTP database why does the statistics histogram for the index PK_TransactionHistory_TransactionID
on table Production.TransactionHistory
only contain 3 histogram "buckets" when there are 113k distinct values in that column?
An example below:
USE AdventureWorks2016
/* ensure statistics are as accurate as they can be */
UPDATE STATISTICS Production.TransactionHistory WITH FULLSCAN
then we can look at the updated histogram
/* look at the statistics for the primary key column */
DBCC SHOW_STATISTICS (
'Production.TransactionHistory',
'PK_TransactionHistory_TransactionID')
WITH HISTOGRAM;
and I see the output:
Note the max and min Transaction IDs:
SELECT MIN(TransactionID) FROM Production.TransactionHistory /* 100000 */
SELECT MAX(TransactionID) FROM Production.TransactionHistory /* 213442 */
SQL Server seems to have created a "bucket" for the max value, one for the min value and one for all the values in between (which it knows are all distinct)
I note that if I remove the primary key from this table
ALTER TABLE Production.TransactionHistory DROP CONSTRAINT PK_TransactionHistory_TransactionID
and then insert some duplicate values
INSERT INTO [Production].[TransactionHistory]
(
TransactionID,
[ProductID],
[ReferenceOrderID],
[ReferenceOrderLineID],
[TransactionDate],
[TransactionType],
[Quantity],
[ActualCost],
[ModifiedDate]
)
VALUES
(200001,1,1,1,GETDATE(),'P',1,1,GETDATE()),
(200011,1,1,1,GETDATE(),'P',1,1,GETDATE()),
(200021,1,1,1,GETDATE(),'P',1,1,GETDATE()),
(200031,1,1,1,GETDATE(),'P',1,1,GETDATE())
Update the stats on the table and then look at the statistic for the column (rather than the PK we have deleted)
USE AdventureWorks2016
/* ensure statistics are as accurate as they can be */
UPDATE STATISTICS Production.TransactionHistory WITH FULLSCAN
/* look at the statistics for the primary key column */
DBCC SHOW_STATISTICS (
'Production.TransactionHistory',
'TransactionID')
WITH HISTOGRAM;
We still have two buckets, though DISTINCT_RANGE_ROWS has updated accordingly
Why does SQL Server not make use of the 200 "buckets" available in a histogram here? Is it something to do with resources required to fill the 8KB statistics page and using all the 200 buckets would mean it may then need to redefine when new data is added to the table?