// SQL snippet

Find rows containing control characters

Match any character in the ASCII 0x01-0x1F control range and list the offending rows; a REPLACE chain is the portable fallback.

Main statement
PostgreSQL
Также охватывает
Oracle

The task

CSV exports break and JSON parsers choke on invisible characters that copy-paste brought into customers.name. Find every row carrying one before the next integration failure.

The snippet

Written for PostgreSQL. Versions for Oracle are under Variations.

PostgreSQL
SELECT id, name,
       LENGTH(name) AS name_length
FROM customers
WHERE name ~ '[\x01-\x1F]'
ORDER BY id;

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

The pattern [\x01-\x1F] matches any character with a code point between 1 and 31: tab (9), newline (10), carriage return (13), and the invisible controls around them. NUL (0) cannot be stored in PostgreSQL text at all, so the range starts at 1. Rows that match are the ones to clean with REPLACE or at the import boundary. The REPLACE chain variant uses CHR(); on MySQL, SQL Server and SQLite write CHAR(9), CHAR(13) and CHAR(10) instead.

Variations

REPLACE chain for tab, CR, LF (PostgreSQL, Oracle)

PostgreSQL Oracle
SELECT id, name
FROM customers
WHERE name IS NOT NULL
  AND name <> REPLACE(REPLACE(REPLACE(
        name, CHR(9), ''), CHR(13), ''), CHR(10), '');

Show which control character each row has

SELECT id, name,
       (REGEXP_MATCHES(name, '[\x01-\x1F]', 'g'))[1] AS control_found
FROM customers
WHERE name ~ '[\x01-\x1F]';

Questions that come up

Why not just trim the column?

Plain TRIM only removes spaces from the ends, so a tab at the start of a name and a newline in the middle both survive it. This query finds control characters wherever they sit, and the REPLACE chain turns into the cleanup when you move it into an UPDATE ... SET name = REPLACE(...).

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.