Login or Sign Up to become a member!

EXPERTS, INFORMATION, IDEAS & KNOWLEDGE

Social bookmarker Add this

Your profile

Search

November 2008
Mon Tue Wed Thu Fri Sat Sun
 << <   > >>
          1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30

XML Feeds

« Good SQL Articles To Read If You Can't Afford BooksFind the last Backup taken in SQL Server »
The Data Management Journal

How to get the selectivity of an index

by SQLDenis


Permalink 20 May 2008 09:32 , Categories: Data Modelling & Design, Database Programming, Database Administration, Microsoft SQL Server Admin, Microsoft SQL Server Tags: database, indexes, optimizing, sql, sqlserver

The selectivity of an index is extremely important. If your index is not selective enough then the optimizer will simply have to do a scan. This is also a reason why creating an index on a gender column does not make a lot of sense.

First create this table

USE tempdb
go

CREATE TABLE TestCompositeIndex (State char(2),Zip Char(5))
INSERT TestCompositeIndex VALUES('NJ','08540')
INSERT TestCompositeIndex VALUES('NJ','08540')
INSERT TestCompositeIndex VALUES('NY','10028')
INSERT TestCompositeIndex VALUES('NY','10021')
INSERT TestCompositeIndex VALUES('NY','10021')
INSERT TestCompositeIndex VALUES('NY','10021')
INSERT TestCompositeIndex VALUES('NY','10001')
INSERT TestCompositeIndex VALUES('NJ','08536')
INSERT TestCompositeIndex VALUES('NJ','08540')

If you have a composite index (composite means the index contains more than one column) you need to run this code.

DECLARE @Count int

SELECT DISTINCT State, Zip
FROM TestCompositeIndex;

SET @Count = @@ROWCOUNT;



SELECT (@Count*1.0) / COUNT(*) AS IndexSelectivity,
COUNT(*)AS TotalCount,
@Count AS DistinctCount
FROM TestCompositeIndex;

Result
——–
IndexSelectivity TotalCount DistinctCount
.555555555555 9 5

If you have a one column index you can use this code

SELECT (COUNT(DISTINCT State)* 1.0) / COUNT(*) AS IndexSelectivity,
COUNT(*) AS TotalCount,
COUNT(DISTINCT State) AS DistinctCount
FROM TestCompositeIndex;

Result
——–
IndexSelectivity TotalCount DistinctCount
.222222222222 9 2

Leave a comment »Send a trackback » 196 views

Trackback address for this post

Trackback URL (right click and copy shortcut/link location)

No feedback yet

Leave a comment


Your email address will not be revealed on this site.

Your URL will be displayed.
PoorExcellent
(Line breaks become <br />)
(Name, email & website)
(Allow users to contact you through a message form (your email will not be revealed.)