Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count number of NULL values in each column in SQL

Tags:

sql

sql-server

I am trying to write a script that will show the number of non-null values in each column as well as the total number of rows in the table.

I have found a couple ways to do this:

SELECT sum(case my_column when null then 1 else 0) "Null Values",
   sum(case my_column when null then 0 else 1) "Non-Null Values"
FROM my_table;

and

SELECT count(*) FROM my_table WHERE my_column IS NULL 
UNION ALL
SELECT count(*) FROM my_table WHERE my_column IS NOT NULL

But these require me to type in each column name manually. Is there a way to perform this action for each column without listing them?

like image 244
TaiwanTimmy Avatar asked Jun 25 '14 14:06

TaiwanTimmy


People also ask

Can we COUNT NULL values in SQL?

Here's the simplest way to count NULL values in SQL The easiest way to count the NULLs in a column is to combine COUNT(*) with WHERE <column name> IS NULL .

Does COUNT 1 include NULL?

2) COUNT(1) What COUNT(1) really does is that it replaces all the records you get from query result with the value 1 and then counts the rows meaning it even replaces a NULL with 1 meaning it takes NULLs into consideration while counting.

Does COUNT distinct COUNT NULLs?

If the COUNT DISTINCT function encounters NULL values, it ignores them unless every value in the specified column is NULL. If every column value is NULL, the COUNT DISTINCT function returns zero (0).

Does COUNT in MySQL COUNT NULL values?

The MySQL COUNT() function provides a number of records in the result set from a table when an SQL SELECT statement is executed. This function does not count the NULL values. The count function gives a BIGINT value.


1 Answers

You should use execute:

DECLARE @t nvarchar(max)
SET @t = N'SELECT '

SELECT @t = @t + 'sum(case when ' + c.name + ' is null then 1 else 0 end) "Null Values for ' + c.name + '",
                sum(case when ' + c.name + ' is null then 0 else 1 end) "Non-Null Values for ' + c.name + '",'
FROM sys.columns c 
WHERE c.object_id = object_id('my_table');

SET @t = SUBSTRING(@t, 1, LEN(@t) - 1) + ' FROM my_table;'

EXEC sp_executesql @t
like image 183
Alireza Avatar answered Sep 22 '22 14:09

Alireza