How to Count Null and Non-Null Values in MySQL


    SUM(IF(col IS NULL, 1, 0)) AS count_nulls, -- counts the nulls in the column

    COUNT(col) AS count_not_nulls -- counts the non-nulls in the column

FROM table_name;

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.

  • By utilizing the SUM function with an IF statement, we count the null values directly: if col is null, the IF statement yields 1; otherwise, it results in 0. The SUM then adds these 1's together to give the total count of null values.
  • The COUNT(col) operation counts all non-null instances in col.

Counting Only Non-Null Values in SQL

For scenarios where only the non-null value count is required, the COUNT function in MySQL simplifies this process:

SELECT COUNT(col) AS count_not_nulls

FROM table_name;

Providing the column name to the COUNT function directly, MySQL returns the number of non-null entries in col, offering a straightforward count of non-null values in the col column from the table_name table.

Counting Only Null Values in SQL Using COUNT

To focus solely on null value counts within a column using MySQL, an efficient technique involves a clever use of the COUNT function:

SELECT (COUNT(*) - COUNT(col)) AS count_nulls

FROM table_name;

This approach uses COUNT(*) to count all rows in the table and subtracts the count of non-null entries in the column col from it. The resultant figure represents the count of null values in the column.

Counting Only Null Values in SQL Using SUM and IF

An alternative method for counting null values employs the SUM function alongside an IF statement for conditional counting:

SELECT SUM(IF(col IS NULL, 1, 0)) AS count_nulls

FROM table_name;

In this technique, the SUM function accumulates the results from the IF statement, which checks each entry in col: if an entry is null, 1 is returned; otherwise, 0 is returned. This effectively provides the total count of null values in the column.

Employing these strategies showcases MySQL's versatility in conducting data aggregation tasks such as counting null and non-null values in a column. Each method caters to different requirements, ensuring you have the right tool for your specific data analysis needs.

Turn your SQL into Beautiful Dashboards

Create amazing KPI dashboards directly from your SQL database with Dashase

  • Create charts, tables, and widgets
  • Collaboration - Shared Dashboards
  • AI assisted query generation - GPT-4
  • Supports PostgreSQL, MySQL, SQL Server, and more

MySQL Snippets