This works for Oracle and SQL Server (you might be able to get it to work on another RDBMS):

select sum(case when a is null then 1 else 0 end) count_nulls
     , count(a) count_not_nulls 
  from us;

Or:

select count(*) - count(a), count(a) from us;
Answer from user155789 on Stack Overflow
🌐
SQL Shack
sqlshack.com › working-with-sql-null-values
Working with SQL NULL values
May 19, 2021 - On the other hand, when we use the COUNT() function with a column name it counts only the non-NULL values in that column.
🌐
Reddit
reddit.com › r/sql › what is a good way to count nulls for all columns in a table?
r/SQL on Reddit: What is a good way to count nulls for all columns in a table?
May 16, 2023 -

I'm working on a building a simple data quality solution where the requirement is to count all nulls for all columns in all tables. We have over 1000 tables. Tried different methods such as looping thru all tables and query each table but it's too expensive and takes forever. Any suggestions?

🌐
W3Schools
w3schools.com › sql › sql_count.asp
SQL COUNT() Function
SQL Examples SQL Editor SQL Quiz SQL Exercises SQL Server SQL Syllabus SQL Study Plan SQL Bootcamp SQL Certificate SQL Training ... The COUNT() function returns the number of rows that matches a specified criterion.
🌐
MakeUseOf
makeuseof.com › home › programming › how to count sql null and not null values in a column
How to Count SQL NULL and NOT NULL Values in a Column
September 3, 2023 - As overwhelming as the NULL value can be. They're actually straightforward to work with. Using COUNT(), you can count your NULL and non-NULL values with just a few lines of SQL codes.
🌐
Quora
quora.com › How-do-you-count-null-values-in-COUNT-function
How to count null values in COUNT() function - Quora
Using COUNT( ) counts the number of non-NULL values of the expression. If you only want to count NULL values, you can use IS NULL in the expression, e.g. COUNT(CASE WHEN IS NULL THEN 1 ELSE N...
🌐
Benjamin's Blog
sqlbenjamin.wordpress.com › 2013 › 12 › 27 › sql-tip-counting-null-values
SQL Tip: COUNTing NULL values – Benjamin's Blog
March 9, 2019 - SELECT LastStatusMessageIDName ,COUNT(1) AS [Count of Total Records] ,COUNT(LastExecutionResult) AS [Count of Non-NULL Records] ,SUM(CASE WHEN LastExecutionResult IS NULL THEN 1 END) AS [Count of NULL Records] FROM dbo.v_ClientAdvertisementStatus ...
🌐
Dashbase
dashbase.ai › sql-snippets › mysql › count-null-and-not-null-values
Count Null and Non-Null Values in MySQL | MySQL
To obtain the count of null and non-null values for a particular column in a MySQL database, you can leverage the COUNT() function in conjunction with conditional aggregation through SUM() and an IF statement.
Find elsewhere
🌐
Navicat
navicat.com › en › company › aboutus › blog › 1796-null-values-and-the-sql-count-function.html
Null Values and the SQL Count() Function
In today's blog, we learned how to combine NULLs with the SQL Count() function to achieve a variety of objectives. More than a way to count NULL and non-NULL values, when combined with other SQL function such as IF() and SUM(), these can be ...
🌐
Dashbase
dashbase.ai › sql-snippets › postgresql › count-null-and-not-null-values
Count Null and Non-Null Values in SQL | PostgreSQL
The SUM function is used to count the null values in the column, and the COUNT function is used to count the non-null values in the column. Inside the sum, we use a CASE statement to check if the value is null, and if it is, we return 1, otherwise we return 0.
🌐
InterSystems
docs.intersystems.com › irislatest › csp › docbook › DocBook.UI.Page.cls
COUNT (SQL) | InterSystems SQL Reference | InterSystems IRIS Data Platform 2025.3
In the COUNT(DISTINCT BY(column) expression) syntax, column specifies the columns whose distinct values are used to filter out duplicate rows before COUNT counts the values in the expression column. This query returns the total number of rows in the Sample.Person table. The count includes rows containing NULL values in one or more columns.
🌐
Quora
quora.com › How-do-I-count-null-values-in-SQL
How to count null values in SQL - Quora
Answer (1 of 6): If you are trying to actually count the nulls then here is a simple solution to that problem. First what field are you trying to count and second what fields are not null for that row. So given this table we will call person which has four columns id, FirstName, LastName, Email....
🌐
SQL Studies
sqlstudies.com › 2018 › 07 › 16 › counting-nulls
Counting NULLs | SQL Studies
June 24, 2018 - Specifically the Quiz: COUNT() in SQL Server. As always I enjoy these quizzes and in this particular case it gave me an idea for a post. ... The ALL argument is the default and is unnecessary (I didn’t even know it existed until I started this post). Here you are counting the number of non NULL values in FieldName.
🌐
Bertwagner
bertwagner.com › data with bert › posts › count distinct and nulls › index
COUNT, DISTINCT, and NULLs
February 19, 2019 - SELECT /* ~~~ will never exist in our data */ COUNT(DISTINCT ISNULL(Col1,'~~~')) FROM ##TestData · The ISNULL here functions the same as the CASE statement in our first attempt, without having to read the table twice. However, that Compute Scalar occurring to the left of our Clustered Index Scan will start to become painful as our data size increases since SQL Server will need to check each and every row and convert any NULLs it finds. Not to mention after computing all of those ~~~ values, SQL Server needs to re-sort the data to be able to find the DISTINCT values.
Top answer
1 of 1
1

The best way to do this would be to construct the query in one shot using STRING_AGG and sys.columns (you should avoid INFORMATION_SCHEMA, it's for compatibility only).

We start off with a basic query for say: Table1 (Col1, Col2), remember that COUNT(something) only counts up non-null values

SELECT
  TableName = 'Table1',
  TotalRows = COUNT(*),
  Col1 = COUNT(Col1),
  Col2 = COUNT(Col2)
FROM Table1

We then unpivot that:

SELECT
  TableName,
  TotalRows,
  NonNullsRows,
  NullsRows = TotalRows - NonNullsRows
FROM (
    SELECT
      TableName = 'Table1',
      TotalRows = COUNT(*),
      Col1 = COUNT(Col1),
      Col2 = COUNT(Col2)
    FROM Table1
) t
UNPIVOT (NonNullsRows FOR Col IN (
    Col1, Col2
)) p

We can then dynamically construct the above for all tables and columns

DECLARE @sql nvarchar(max) =
(
    SELECT STRING_AGG(TableQuery, N'
UNION ALL
')
    FROM (
        SELECT N'
SELECT
  TableName,
  Col as ColumnName,
  TotalRows,
  NonNullsRows,
  NullsRows = TotalRows - NonNullsRows
FROM (
    SELECT
      TableName = ' + QUOTENAME(t.name, '''') + N',
      TotalRows = COUNT(*),
      ' + STRING_AGG(CAST(QUOTENAME(c.name) + ' = COUNT(' + QUOTENAME(c.name) + ')' AS nvarchar(max)), ',') + N'
    FROM ' + QUOTENAME(SCHEMA_NAME(t.schema_id)) + '.' + QUOTENAME(t.name) + N'
) t
UNPIVOT (NonNullsRows FOR Col IN 
    (' + STRING_AGG(CAST(QUOTENAME(c.name) AS nvarchar(max)), ',') + N'
)) p'

        FROM sys.tables t
        JOIN sys.columns c ON c.object_id = t.object_id
        WHERE c.name LIKE 'new_'   -- do you want this filter
           -- you may also want AND c.is_nullable = 1
        GROUP BY t.object_id, t.name, t.schema_id

    ) AS t(TableQuery)
);

PRINT @sql;  -- for testing

EXEC sp_executesql @sql;
🌐
SQL Authority
blog.sqlauthority.com › home › sql server – count null values from column
SQL SERVER - Count NULL Values From Column - SQL Authority with Pinal Dave
April 29, 2020 - SELECT SUM(CASE WHEN XourColumn IS NULL THEN 1 ELSE 0 END) * 100.0 / COUNT(*) AS is_null_percent FROM YourDatabase; I’m using it to find index with a lot of NULLsReply ... Pinal Dave is an SQL Server Performance Tuning Expert and independent consultant with over 22 years of hands-on experience.
Top answer
1 of 1
4

Right from the MySQL Documentation

COUNT(expr) [over_clause]

Returns a count of the number of non-NULL values of expr in the rows retrieved by a SELECT statement. The result is a BIGINT value.

If there are no matching rows, COUNT() returns 0.

Just use COUNT() function on each column and add them up last

SELECT
   id,COUNT(val1)+COUNT(val2)+COUNT(val3) count_non_null_vals
FROM mytable;

You can use your PHP / Python / Java to craft the SQL since you have 30 columns.

UPDATE 2021-09-20 11:45 EDT

I decided to actually write this out for real. Here is what I did:

MY PROPOSED QUERY

SET session sql_mode = '';
SELECT IFNULL(id,'') all_ids
,COUNT(val1)+COUNT(val2)+COUNT(val3) count_non_null_vals
FROM mytable GROUP BY id WITH ROLLUP;

YOUR SAMPLE DATA

DROP DATABASE IF EXISTS codemonkey;
CREATE DATABASE codemonkey;
USE codemonkey
CREATE TABLE mytable
(
    id INT NOT NULL AUTO_INCREMENT,
    firstname VARCHAR(20),
    surname VARCHAR(20),
    val1 INT DEFAULT NULL,
    val2 INT DEFAULT NULL,
    val3 INT DEFAULT NULL,
    PRIMARY KEY (id)
);
INSERT INTO mytable (firstname,surname,val1,val2,val3) VALUES
('joe','blogs',1,NULL,NULL),
('jane','doe',NULL,2,5),
('bobby','tables',NULL,NULL,NULL);
SELECT * FROM mytable;

YOUR SAMPLE DATA LOADED

mysql> DROP DATABASE IF EXISTS codemonkey;
Query OK, 1 row affected (0.03 sec)

mysql> CREATE DATABASE codemonkey;
Query OK, 1 row affected (0.00 sec)

mysql> USE codemonkey
Database changed
mysql> CREATE TABLE mytable
    -> (
    ->     id INT NOT NULL AUTO_INCREMENT,
    ->     firstname VARCHAR(20),
    ->     surname VARCHAR(20),
    ->     val1 INT DEFAULT NULL,
    ->     val2 INT DEFAULT NULL,
    ->     val3 INT DEFAULT NULL,
    ->     PRIMARY KEY (id)
    -> );
Query OK, 0 rows affected (0.01 sec)

mysql> INSERT INTO mytable (firstname,surname,val1,val2,val3) VALUES
    -> ('joe','blogs',1,NULL,NULL),
    -> ('jane','doe',NULL,2,5),
    -> ('bobby','tables',NULL,NULL,NULL);
Query OK, 3 rows affected (0.01 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql>

YOUR TABLE

mysql> SELECT * FROM mytable;
+----+-----------+---------+------+------+------+
| id | firstname | surname | val1 | val2 | val3 |
+----+-----------+---------+------+------+------+
|  1 | joe       | blogs   |    1 | NULL | NULL |
|  2 | jane      | doe     | NULL |    2 |    5 |
|  3 | bobby     | tables  | NULL | NULL | NULL |
+----+-----------+---------+------+------+------+
3 rows in set (0.00 sec)

mysql>

MY PROPOSED QUERY EXECUTED

mysql> SET session sql_mode = '';
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> SELECT IFNULL(id,'') all_ids
    -> ,COUNT(val1)+COUNT(val2)+COUNT(val3) count_non_null_vals
    -> FROM mytable GROUP BY id WITH ROLLUP;
+---------+---------------------+
| all_ids | count_non_null_vals |
+---------+---------------------+
| 1       |                   1 |
| 2       |                   2 |
| 3       |                   0 |
|         |                   3 |
+---------+---------------------+
4 rows in set (0.01 sec)

mysql>

BIG CAVEAT

I had to set the session's sql_mode to blank because MySQL does not like doing aggregate queries of this nature. It complains of an invalidate GROUP BY otherwise.

UPDATE 2021-09-20 12:03 EDT

For those running 5.7/8.0, you can disable sql_mode in the session, run the query and reset it back ....

SET @old_sql_mode = @@session.sql_mode;
SET session sql_mode = '';
SELECT IFNULL(id,'') all_ids
,COUNT(val1)+COUNT(val2)+COUNT(val3) count_non_null_vals
FROM mytable GROUP BY id WITH ROLLUP;
SET session sql_mode = @old_sql_mode;