I\'ve inherited a legacy database, and many, many fields are no longer being used. I can tell by querying on the last couple of years and seeing which fields are null, to at
This gives you the count of all records with NULL fields which you can compare to the count of all the records
SELECT COUNT(*)
FROM Table1
WHERE COALESCE (Field1, Field2, etc) IS NULL
Is this what you need?
SELECT count(*)
FROM table
WHERE field IS NULL
or of course
SELECT SUM(CASE WHEN field IS NULL THEN 1 ELSE 0 END) AS [field is null count]
COUNT(*) as [total count]
FROM table
also works and you can do it for a bunch of fields at once.
Stealing Aaron Bertrand's template:
DECLARE @tableName NVARCHAR(512)
SET @tableName = N'dbo.tablename';
DECLARE @sql NVARCHAR(MAX);
SELECT @sql = N'';
SELECT @sql = @sql + N' SUM(CASE WHEN ' + QUOTENAME(name) + ' IS NULL THEN 1 ELSE 0 END) AS ['+name+' null count], '
FROM sys.columns
WHERE object_id = OBJECT_ID(@tableName) AND is_nullable = 1;
SELECT @sql = 'SELECT ' + @sql + ' Total_Count = COUNT(*)
FROM ' + @tableName + ';';
EXEC sp_executesql @sql;
DECLARE @table NVARCHAR(512);
SET @table = N'dbo.tablename';
DECLARE @sql NVARCHAR(MAX);
SELECT @sql = N'';
SELECT @sql = @sql + QUOTENAME(name)
+ ' = SUM(CASE WHEN ' + QUOTENAME(name) + ' IS NULL THEN 1 ELSE 0 END),'
FROM sys.columns
WHERE object_id = OBJECT_ID(@table)
AND is_nullable = 1;
SELECT @sql = 'SELECT ' + @sql + ' Total_Count = COUNT(*)
FROM ' + @table + ';';
EXEC sp_executesql @sql;
Any columns that come out 0 have all nulls (unless the Total_Count column also comes out 0, in which case the table is empty). Note that this query will be pretty expensive on a large table.