The fastest way to remove invalid characters in SQL is to apply a whitelist: keep only the characters you explicitly allow, replace or delete everything else. In most engines that means a nested REPLACE chain for a small fixed set, or a regular-expression function for anything broader. SQL Server's TRANSLATE and modern REGEXP_REPLACE in PostgreSQL, MySQL 8+, and Oracle make this a one- or two-line job, while older MySQL and SQLite need a different approach. The key condition is that you must define "invalid" before you write any code, because the database can't guess whether a symbol is a typo, a foreign accent, or legitimate data.
Start by defining what "invalid" actually means
"Invalid character" isn't a database concept; it's a business rule. A character that breaks a downstream CSV export may be perfectly valid in the database itself. Before filtering anything, write down the rule in one sentence: for example, "Latin letters, digits, spaces, and the symbols . , ' - _ @ are allowed; everything else is invalid." That sentence becomes your function's contract and your acceptance test.
There are three distinct kinds of "invalid" worth separating, because they need different tools:
Out of the allowed set — an emoji or a curly quote where only ASCII is permitted. This is a whitelist job, handled by the pattern functions below. Invisible or control characters — tabs, carriage returns, zero-width spaces pasted in from a web form. These usually pass visual inspection and need explicit pattern treatment or TRIM-style cleanup. Encoding breakage — mojibake such as é where é was intended. That's an import problem, not a filtering problem; scrubbing the characters after the fact loses information you may need to recover first.
The third category is the one people most often misdiagnose. If you strip every non-ASCII byte from a mangled string, you've destroyed the evidence that a UTF-8 file was read as Latin-1. Fix the load path first, then filter. For the other two categories, filtering at write time (in the insert or update, or via a constraint) is safer than cleaning after the fact, because otherwise bad rows keep arriving.
The whitelist pattern: the core technique
Nearly every SQL dialect now supports some form of regex replacement, and the whitelist idiom is the same everywhere: match one character that is not in the allowed class, and replace it with nothing or with a placeholder.
The mechanics are worth spelling out because the syntax varies:
1: Build a character class containing only what you allow, in square brackets. Use ranges where they're safe: [A-Za-z0-9] for letters and digits. 2: Negate the class with ^ so it matches the disallowed characters instead: [^A-Za-z0-9 .'@_-]. 3: Replace matches with an empty string to delete them, or with a space or underscore to keep word boundaries intact. 4: Anchor the operation to the column you're cleaning and test it against a sample before running it across a table.
Here is the same idea in the major engines, all using an "allow letters, digits, spaces, period, comma, hyphen, underscore, apostrophe, at-sign" rule:
PostgreSQL: REGEXP_REPLACE(col, '[^A-Za-z0-9 .,''@-]', '', 'g') MySQL 8.0+: REGEXP_REPLACE(col, '[^A-Za-z0-9 .,''@-]', '') — the global behavior is the default there. Oracle: REGEXP_REPLACE(col, '[^A-Za-z0-9 .,''@-]', '') with the same semantics. SQL Server 2025 and Azure SQL: REGEXP_REPLACE(col, '[^A-Za-z0-9 .,''@-]', '').
Two details bite people in practice. First, the hyphen must go at the end of the class (or be escaped) or it becomes a range, and [^A-Za-z0-9 -] silently allows every character between space and underscore. Second, the apostrophe needs doubling inside a SQL string literal in every dialect; in PostgreSQL you can alternatively use dollar quoting, $re$[^A-Za-z0-9 .,'@-]$re$, which avoids the doubling entirely. Case sensitivity also matters: in PostgreSQL [A-Za-z] is explicit and safe, while the POSIX classes [:alpha:] and [:alnum:] are clearer if you want locale-aware letters and digits.
Filtering without regex: nested REPLACE and TRANSLATE
Not every engine has regex, and even where it exists, a small fixed set of replacements is sometimes clearer and faster. Two approaches cover this.
Nested REPLACE works everywhere, including SQLite and older MySQL. You stack one REPLACE per character, remembering that each call only replaces its own character and the order doesn't matter for single-character removal. Cleaning tabs, carriage returns, and line feeds from SQLite looks like this:
This is fine for three to five characters. Beyond that it becomes unreadable, and it's O(characters × length) work per row.
TRANSLATE is the better tool for character-to-character mapping and is available in SQL Server (2017+), Oracle, and PostgreSQL 9.5+. It maps each character in the first argument to the character at the same position in the second, and deletes characters in the first that have no counterpart in the second. That last behavior is a compact deletion trick: translate a set of unwanted characters to nothing. In SQL Server, TRANSLATE(col, 'abc', 'xyz') swaps each letter; TRANSLATE(col, 'éàü', 'eau') strips accents without a regex. A related idiom is replacing every disallowed character with a sentinel and then cleaning up runs, which is useful when you want to collapse multiple invalid characters into a single underscore rather than gluing words together.
The limitation: TRANSLATE can't express ranges. You either enumerate the characters or use regex.
SQL Server: patterns and alternatives
SQL Server is the odd one out historically because PATINDEX supports only a limited wildcard character class and no general regex, which is why the classic workaround is a nested-REPLACE chain or a user-defined function. In older versions the common pattern is a T-SQL function that loops over a list of allowed characters, building an output string one character at a time — accurate but slow on large tables.
SQL Server 2025 changed this by adding REGEXP_REPLACE, which accepts an optional start position and a match number, so you can replace all matches of the pattern. If you're on 2022 or earlier, plan for either a CLR function or a set-based workaround: split the string into characters using a numbers table or CROSS APPLY with SUBSTRING, filter rows where the single character LIKE your allowed pattern, and re-aggregate with STRING_AGG. That's the honest answer to "how do I filter invalid characters in SQL Server" — the tooling depends on the version, and version-specific syntax should be verified against the documentation for the release you're actually running.
Using a lookup table for large or changing invalid sets
When the invalid set is large, policy-driven, or changes frequently, hardcoding it in SQL is a maintenance trap. A small table of allowed code points (with a category and a replacement) and a CROSS APPLY or join to a string-splitting function is more maintainable. You change data, not code, when policy changes, and you can log which characters were stripped.
The typical shape is: a allowed_chars table with one row per accepted character (plus category, such as letter, digit, punctuation, space), a function that expands a string into its characters, an anti-join to find characters not in the table, and a STRING_AGG (PostgreSQL, SQL Server, Oracle) or GROUP_CONCAT (MySQL) to reassemble. The cost is more moving parts; the benefit is that the rule lives in data and can be audited. For a one-off migration, inline pattern functions are simpler. For a long-lived ingest pipeline, the table pays for itself the first time the policy changes.
Cleaning before and after the filter
Character filtering usually happens as part of a broader normalization sequence, and order matters. A workable order for a data-cleaning update is:
1: Confirm the data types and the column's collation or encoding; fixing encoding belongs here, not later. 2: Normalize whitespace: collapse runs of spaces, trim leading and trailing spaces, and convert tabs to spaces if tabs are allowed at all. 3: Remove or replace the characters outside the allowed set with the whitelist technique. 4: Re-trim, because replacing an invalid character with nothing can leave doubled spaces or a leading/trailing delimiter. 5: Optionally collapse repeated separators and validate the result against a format check (for example, a pattern for an email local part).
Skipping step 4 is the most common cause of "I cleaned the data and now there are double spaces." If you replace invalid characters with a space instead of deleting them, you must collapse whitespace afterward; if you delete them, you must re-trim.
A worked example with a real check
Suppose a table signups has a display_name column, and the rule is letters, digits, spaces, hyphens, and underscores. In PostgreSQL you would first measure the problem and preserve evidence before changing anything:
Then clean, writing to a new column or a staging table first so the original is preserved:
Success check: rerun the first count against the cleaned column; it should return zero, and a spot-check query comparing original and cleaned values should show only the intended removals. If your count doesn't drop to zero, the usual causes are an unescaped hyphen creating (or breaking) a range, an invisible character that the pattern class accidentally allows, or a case mismatch in the pattern. A useful diagnostic is to reverse the test — select the distinct characters remaining that are outside the allowed set using a per-character split — rather than guessing at the pattern.
Because this is an ordinary data-hygiene task, the numbers you'll see depend entirely on your data and rule, so treat any specific counts above as illustrative rather than benchmarks.
Traps, edge cases, and what the filter should not do
A few failure modes deserve naming because they're easy to introduce and hard to notice:
Over-filtering legitimate names. O'Brien, Nguyễn, van der Berg, and İstanbul all contain characters a naive ASCII whitelist would mangle. If the column holds human names, strip only control characters and clearly malicious input, and validate with a format rather than an aggressive allowlist. Security theater. Filtering characters does not make SQL injection safe; parameterized queries do. Similarly, HTML-escaping in a database is usually the wrong layer, because you don't know whether the consumer is HTML, JSON, or plain text. Collation and encoding mismatches. In MySQL, REGEXP_REPLACE behavior depends on the string's collation, and in PostgreSQL, comparing or matching text with a non-C collation can make character classes behave differently than you expect. Test with real data from your own server version, not from a generic example. Silent data loss in bulk updates. Run the cleaning as a SELECT first, compare row counts and checksums, and stage the update. A pattern that's slightly too broad will quietly delete meaning from a column overnight. Performance. Regex replacement on millions of rows is CPU-bound; batch the update, index the predicate used to find dirty rows, and consider computing the clean value once at insert time rather than re-running cleanup in every report. Idempotence. A good filter produces the same result when run twice. Test that; if a second pass changes the output, your replacement character or whitespace collapse has a bug.
The deeper point is that "invalid" is contextual, and the SQL functions are dumb tools. The judgment about which characters matter lives in your schema constraints and your data contract, not in the regex. Put a CHECK constraint or trigger on the column so bad characters can't re-enter, and keep the cleaning function in version control alongside the rule it encodes.
Practical defaults by engine
If you want a starting point rather than a design exercise, these defaults hold up for most text columns:
PostgreSQL: regexp_replace(col, '[[:cntrl:]]', '', 'g') to drop control characters, then a whitelist pattern per column type. Use [^[:print:]] cautiously — it also strips non-ASCII accented letters, which may be legitimate. MySQL 8+: REGEXP_REPLACE behaves globally by default; watch the collation and note that REGEXP_REPLACE isn't available in 5.7 and earlier, where nested REPLACE is the fallback. SQL Server: TRANSLATE for known character substitutions, REPLACE chains for a few symbols, and REGEXP_REPLACE if you're on 2025 or Azure SQL. Oracle: REGEXP_REPLACE with the 'g'-equivalent default behavior, plus TRANSLATE for accent folding. SQLite: no built-in regex; use nested REPLACE, a custom function, or clean the data before insert in the application layer.
In every case the workflow is the same: define the allowed set, test the pattern against samples, stage the update, verify zero remaining violations, then enforce the rule at the schema so the problem doesn't come back.