SQL Count NULLs


This entry is part 4 of 4 in the series SQL Count

How many NULLs are there in a column? What would the SQL query be? For small tables you could could literally count them from a SELECT statement. For larger tables, you will need a query.

The Microsoft Press book T-SQL Querying by Ikzik Ben-Gan et al has an example table called Orders that you could use in a non-production server. We could use this table to illustrate the basics of COUNT. The script below creates the table and populates it with a bit of data.

CREATE TABLE dbo.Orders(
  orderid INT     NOT NULL,
  custid  CHAR(5)     NULL);
go
INSERT INTO dbo.Orders(orderid, custid) VALUES
  (1, 'FRNDO'),
  (2, 'FRNDO'),
  (3, 'KRLOS'),
  (4, 'KRLOS'),
  (5, 'KRLOS'),
  (6, 'MRPHS'),
  (7, NULL   );

Let’s count all of the NULLs in a column.

SELECT COUNT(*) AS 'Count all', 
   COUNT(custid) AS 'Count of Non-null customers', 
   COUNT(*) - COUNT(custid) AS 'Nulls'
FROM dbo.Orders

With WHERE clause

One way to count the NULLs in a column is to combine COUNT(*) with WHERE IS NULL .

SELECT COUNT(*) AS num_nulls
FROM dbo.Orders
WHERE custid IS NULL
Series Navigation<< SQL Server Count Duplicates