How to: SQL Count Null

How to: SQL Count Null

When working with databases, you may come across situations where you need to determine the number of null values in a column. One way to accomplish this is by using the COUNT() function in SQL. In this tutorial, you’ll learn how to use the COUNT() function to count null values in a column.

Prerequisites

Before you begin, it’s assumed that you have a basic understanding of SQL and how to write basic SQL queries. It’s also important that you have access to a database and a table to work with.

Syntax

The syntax for using the COUNT() function to count null values in a column is as follows:

SELECT COUNT(column_name)
FROM table_name
WHERE column_name IS NULL;

In the above syntax, column_name is the name of the column you want to count the null values for, and table_name is the name of the table that contains the column.

Example

Suppose you have a table named employees with the following schema:

Column NameData Type
idINT
nameVARCHAR
departmentVARCHAR
salaryINT

To count the number of null values in the department column, you would use the following query:

SELECT COUNT(department)
FROM employees
WHERE department IS NULL;

The output of the query would be a single row with a single column that contains the count of null values in the department column.

Troubleshooting Tips

  • Make sure that you have spelled the column name and table name correctly in your query.

  • Ensure that you have selected the correct database and table.

  • If you are still having trouble getting the expected results, try using a different column to count the null values for to see if the issue is specific to the column you are trying to count null values for.

Conclusion

Using the COUNT() function to count null values in a column is a simple task that can be accomplished with just a few lines of SQL code. By following the syntax outlined in this tutorial and using the troubleshooting tips provided, you should be able to successfully count null values in any SQL database.