// SQL snippet

Find blank strings mixed with NULLs

One row counts the kinds of 'no value' per column: real NULLs, empty strings, and blanks (empty or nothing but spaces).

Main statement
All engines

The task

Legacy imports wrote '' instead of NULL, so customers.name is now a mix of both. Any IS NULL check undercounts the real holes until you know the split.

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 name = '' THEN 1 ELSE 0 END) AS empty_name,
  SUM(CASE WHEN name IS NOT NULL
            AND (TRIM(name) = '' OR TRIM(name) IS NULL)
           THEN 1 ELSE 0 END) AS blank_name
FROM customers;

Как это работает

Each SUM(CASE) tests one definition of missing: IS NULL for true NULLs, = '' for empty strings, and a trimmed value that is empty for blanks, which includes the empty strings. The TRIM(name) IS NULL branch is there for Oracle, where TRIM(' ') returns NULL rather than ''. Repeat the expressions per suspect column; the split tells you whether to normalize before adding NOT NULL or validation constraints. Expect different numbers per engine on the same data: Oracle stores '' as NULL, so empty_name is always 0 and those rows show up as NULLs, and SQL Server ignores trailing spaces when comparing, so its empty_name already counts ' '.

Variations

Normalize blanks to NULL (after the audit)

UPDATE customers
SET name = NULL
WHERE name IS NOT NULL
  AND (TRIM(name) = '' OR TRIM(name) IS NULL);

Questions that come up

Why does Oracle report no empty strings?

Oracle treats a zero-length VARCHAR2 as NULL: inserting '' stores NULL, and name = '' is never true. Those rows land in null_name instead. Every other engine here keeps '' and NULL apart, which is why the same import can look clean on Oracle and messy on PostgreSQL.

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.