Technical Article

SP for checking column uniqueness

,

When creating indexes on tables, it is always best to choose columns that have a high degree of selectivity, or uniqueness.  This SP, ShowUniqueness, gives the user an easy way to determine the "uniqueness" percentage of a given column or combination of columns.

CREATE PROCEDURE ShowUniqueness
/*
Shows the percentage of unique values in a column, so that you can determine if it is a candidate for indexing.

Syntax: EXEC ShowUniqueness 'MyTable', 'Column1'

You can also pass a concatenation of multiple columns.  Non-char columns must be CAST.

Example: EXEC ShowUniqueness 'MyTable', 'Column1 + Column2 + CAST(Column3 AS varchar)'
*/
@tbl sysname, 
@col sysname

AS

EXEC
(
'SELECT ((SELECT COUNT(DISTINCT ' + @col + ') 
FROM ' + @tbl + ') * 100) /
(SELECT rows FROM sysindexes 
WHERE id = OBJECT_ID(''' + @tbl + ''') AND indid < 2) 
AS percent_unique'
)

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating