Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: Select columns WITHOUT NULL values only in a table

This question is the exact opposite of SQL: Select columns with NULL values only.

Given a table with 1024 columns, how to find all columns WITHOUT null values?

Input:a table with 1024 columns

Output:col1_name(no null values) col2_name(no null values)...

like image 792
Jill Clover Avatar asked Sep 10 '26 13:09

Jill Clover


1 Answers

If you want to avoid using a CURSOR, this method will simply list out the column names of any columns that have no NULL values in them anywhere in the table... just set the @TableName at the top:

DECLARE @tableName sysname;
DECLARE @sql nvarchar(max);
SET @sql = N'';
SET @tableName = N'Reports_table';

SELECT @sql += 'SELECT CASE WHEN EXISTS (SELECT 1 FROM ' + @tableName + ' WHERE '+ COLUMN_NAME + ' IS NULL) THEN NULL ELSE ''' + COLUMN_NAME +
''' END AS ColumnsWithNoNulls UNION ALL '
FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @tableName
SELECT @sql = SUBSTRING(@sql, 0, LEN(@sql) - 10);
IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results;
CREATE TABLE #Results (ColumnsWithNoNulls sysname NULL);
INSERT INTO #Results EXEC(@sql);
SELECT * FROM #Results WHERE ColumnsWithNoNulls IS NOT NULL

As a bonus, the results are in a temp table, #Results, so you can query to get any information you want... counts, etc.

like image 62
pmbAustin Avatar answered Sep 12 '26 04:09

pmbAustin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!