Skip to content

Instantly share code, notes, and snippets.

@tcartwright
Last active October 23, 2025 13:29
Show Gist options
  • Save tcartwright/9c167fc7082e3bd994a93c2d9ccf77e4 to your computer and use it in GitHub Desktop.
Save tcartwright/9c167fc7082e3bd994a93c2d9ccf77e4 to your computer and use it in GitHub Desktop.
SQL SERVER: Get tables data distribution for help with index creation
DECLARE @table SYSNAME = '[dbo].[TableName]';
DECLARE @sql NVARCHAR(MAX) = N'';
DECLARE @RowCount BIGINT;
-- Get total row count once (no need to scan per column)
SELECT @RowCount = SUM(p.[rows])
FROM sys.partitions AS p
WHERE p.[object_id] = OBJECT_ID(@table)
AND p.[index_id] IN (0, 1); -- heap or clustered index
SELECT @sql =
STUFF((
SELECT CONCAT(
'
UNION ALL
SELECT
''', c.name, ''' AS [ColumnName],
', @RowCount, ' AS [RowCount],
COUNT(DISTINCT [', c.name, ']) AS [DistinctCount],
CAST(COUNT(DISTINCT [', c.name, ']) * 100.0 / ', @RowCount, ' AS DECIMAL(10,2)) AS [DistinctPct],
SUM(CASE WHEN [', c.name, '] IS NULL THEN 1 ELSE 0 END) AS [NullCount],
CAST(SUM(CASE WHEN [', c.name, '] IS NULL THEN 1 ELSE 0 END) * 100.0 / ', @RowCount, ' AS DECIMAL(10,2)) AS [NullPct]
FROM ', @table, ' WITH (NOLOCK)'
)
FROM sys.columns AS c
WHERE c.[object_id] = OBJECT_ID(@table)
ORDER BY c.[column_id]
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 11, '');
PRINT @sql;
EXEC sys.sp_executesql @sql;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment