// SQL snippet

Count NULLs per column (NULL skew)

Build one summary row that counts NULLs per column, so a quick scan shows which columns carry missing data.

Main statement
All engines

The task

Before trusting customers for analytics you want to know how much of each column is actually populated, and whether some column is almost entirely NULL, a skew that usually means a broken upstream feed.

The snippet

Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.

All engines
SELECT
  COUNT(*) AS total_rows,
  SUM(CASE WHEN name IS NULL THEN 1 ELSE 0 END) AS null_name,
  SUM(CASE WHEN email IS NULL THEN 1 ELSE 0 END) AS null_email,
  SUM(CASE WHEN phone IS NULL THEN 1 ELSE 0 END) AS null_phone,
  SUM(CASE WHEN created_at IS NULL THEN 1 ELSE 0 END) AS null_created_at
FROM customers;

작동 방식

Each SUM(CASE ...) adds 1 only for rows where that column is NULL, producing a wide one-row report. COUNT(*) is the denominator, so null_email / total_rows is the NULL rate. Add one line per column you care about; wide tables are easier with the unpivoted variant.

Variations

One row per column (UNION ALL)

SELECT 'name' AS column_name,
       SUM(CASE WHEN name IS NULL THEN 1 ELSE 0 END) AS null_count,
       COUNT(*) AS total_rows
FROM customers
UNION ALL
SELECT 'email',
       SUM(CASE WHEN email IS NULL THEN 1 ELSE 0 END),
       COUNT(*)
FROM customers
UNION ALL
SELECT 'phone',
       SUM(CASE WHEN phone IS NULL THEN 1 ELSE 0 END),
       COUNT(*)
FROM customers;

Questions that come up

Why SUM(CASE) instead of COUNT(col)?

COUNT(col) counts non-NULL values, so COUNT(*) - COUNT(col) is the NULL count: a shorter form of the same answer, and the per-column-fill-rate recipe uses it. The CASE form is spelled out here because the same shape extends to other conditions in the same row, such as counting empty strings with CASE WHEN col = '' THEN 1 END.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.