Skip to content

SQL - PostgreSQL - Replace Empty Strings with NULLs

Source: sql-snippets/replace-empty-strings-null.md at main · count/sql-snippets (github.com)

Explore this snippet here.

Description

An essential part of cleaning a new data source is deciding how to treat missing values. The CASE statement can help with replacing empty values with something else:

WITH data AS (
  SELECT *
  FROM (VALUES ('a'), ('b'), (''), ('d')) AS data (str)
)

SELECT
  CASE WHEN LENGTH(str) != 0 THEN str END AS str
FROM data;

Output:

str
a
b
NULL
d

Backlinks:

list from [[SQL - PostgreSQL - Replace Empty Strings with NULLs]] AND -"Changelog"