// SQL snippet

Remove non-printable and control characters in SQL

Pasted text often carries zero-width characters, form feeds or stray control bytes that break matching and exports. Strip them down to printable text.

Main statement
PostgreSQL
还支持
SQL Server Oracle

The task

Free-text fields accumulate control characters from copy-paste and imports. They are invisible on screen but break joins, exports and full-text search.

The snippet

Written for PostgreSQL. Versions for SQL Server and Oracle are under Variations.

PostgreSQL
SELECT REGEXP_REPLACE(comment_text, '[^' || chr(32) || '-' || chr(126) || ']', '', 'g') AS clean_text
FROM comments;

工作原理

The pattern matches any character outside the printable ASCII range (space through tilde) and deletes it, so control characters, zero-width spaces and every non-ASCII letter go. This is the strictest form. If you want to keep accented letters, delete only the control range instead: '[[:cntrl:]]' on PostgreSQL and Oracle.

Variations

Oracle

Oracle
SELECT REGEXP_REPLACE(comment_text, '[^' || CHR(32) || '-' || CHR(126) || ']', '') AS clean_text
FROM comments;

SQL Server 2022 and older (no regex: remove tab, LF, CR)

SQL Server
SELECT REPLACE(REPLACE(REPLACE(comment_text, CHAR(9), ''), CHAR(10), ''), CHAR(13), '') AS clean_text
FROM comments;

Questions that come up

Does this delete accented letters and emojis?

Yes, the strict pattern keeps ASCII printable characters only. That is usually what you want for codes and keys, but for human text prefer a pattern that keeps non-ASCII letters and only drops control characters. SQL Server 2025 adds REGEXP_REPLACE, which replaces every match by default: REGEXP_REPLACE(comment_text, '[^ -~]', '') is the same strict filter there.

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.