BBampaa

Lessons › SQL › Chapter 9: Data Cleaning

SQL lesson

Counting NULLs per column with SUM(CASE WHEN ... IS NULL)

Before you clean a table, find out how much is missing. CASE WHEN email IS NULL THEN 1 ELSE 0 END gives each row a 1 if its email is empty, and a 0 if it's there. SUM adds up the 1s: that's how many emails are missing. Do it once per column to see every gap in one row.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

How many empty cells in each column?

SELECT SUM(CASE WHEN email IS NULL THEN 1 ELSE 0 END) AS missing_email,
       SUM(CASE WHEN phone IS NULL THEN 1 ELSE 0 END) AS missing_phone
FROM customers

Result:

missing_emailmissing_phone
21

Step by step

  1. 1 if the email is empty, 0 if it's there.
    SELECT SUM(CASE WHEN email IS NULL THEN 1 ELSE 0 END) AS missing_email FROM customers
  2. Adds up the 1s: how many are missing.
    SELECT SUM(CASE WHEN email IS NULL THEN 1 ELSE 0 END) AS missing_email FROM customers
  3. Repeat it for each column, with a comma between.
    SELECT SUM(CASE WHEN email IS NULL THEN 1 ELSE 0 END) AS missing_email, SUM(CASE WHEN phone IS NULL THEN 1 ELSE 0 END) AS missing_phone FROM customers

Practice

Try each one in your head first, then open the answer.

1. Using customers, count how many emails are missing. Name it missing_email.
SELECT SUM(CASE WHEN email IS NULL THEN 1 ELSE 0 END) AS missing_email FROM customers
2. Now count missing phones too, in the same row. Name it missing_phone.
SELECT SUM(CASE WHEN email IS NULL THEN 1 ELSE 0 END) AS missing_email, SUM(CASE WHEN phone IS NULL THEN 1 ELSE 0 END) AS missing_phone FROM customers
3. Using orders, count how many orders have no discount recorded. Name it missing_discount.
SELECT SUM(CASE WHEN discount IS NULL THEN 1 ELSE 0 END) AS missing_discount FROM orders
4. Using shipments, count the missing ship_date and missing weight_kg values in one row. Name them missing_ship_date and missing_weight.
SELECT SUM(CASE WHEN ship_date IS NULL THEN 1 ELSE 0 END) AS missing_ship_date, SUM(CASE WHEN weight_kg IS NULL THEN 1 ELSE 0 END) AS missing_weight FROM shipments
5. Using employees, for each department, count how many employees have no salary recorded. Name it missing_salary.
SELECT department, SUM(CASE WHEN salary IS NULL THEN 1 ELSE 0 END) AS missing_salary FROM employees GROUP BY department

Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.

Try this lesson free →
About 5–10 minutes · no sign-up needed