Fix PostgreSQL Error 22021: Invalid Character in String
In this article
The PostgreSQL error 22021 ("character not in repertoire") means your application or script is reading a string that contains characters outside PostgreSQL’s current character set (often UTF-8). This blocks operations like inserts, updates, or queries. The fix depends on whether the issue is in your data source, application code, or database configuration—but here’s the practical path to resolve it.
What You'll Need
- A working PostgreSQL client (psql, pgAdmin, or application tool like Python’s `psycopg2`)
- Access to the database (or a backup if you modify data)
- Basic familiarity with SQL commands (for manual fixes) or your app’s configuration
- If reading from files, the raw text containing problematic characters
Step-by-Step
-
Identify the problematic string.
Use a hex dump or text editor to inspect the string causing the error. In psql, run:
SELECT hex(your_column) FROM your_table WHERE your_condition;(Replace `your_column` and `your_table` with actual names.) This shows raw byte values.Example: If hex showse28080, it’s likely a surrogate character (e.g., from malformed UTF-8). -
Check your database encoding.
Run:
SELECT setting FROM pg_settings WHERE name = 'client_encoding';If it returnsS-1,ISO-8859-1, or a legacy encoding, update it to UTF-8:ALTER SYSTEM SET client_encoding TO 'UTF8';Then restart PostgreSQL (or apply to a running server viaSELECT pg_reload_conf();). -
Fix the data source (if applicable).
- For file imports: Ensure the file is properly encoded with UTF-8. Use:
iconv -f(Replace-t UTF-8 input.csv > output.csv source_encodingwith the actual encoding, e.g.,windows-1252.) - For application code: Strip or encode problematic characters. Example in Python:
import re; clean_text = re.sub(r'[^\x00-\x7F]', '', bad_string)(This removes non-ASCII; adjust regex for your needs.)
- For file imports: Ensure the file is properly encoded with UTF-8. Use:
-
Update your application query.
Explicitly set the encoding for the connection or query. In Python with
psycopg2:import psycopg2; conn = psycopg2.connect("dbname=test user=postgres password=xxx", Encoding="UTF8")Or use a parameterized query to avoid string injection:cursor.execute("INSERT INTO table (col) VALUES (%s)", [clean_data]); -
Recreate the table with UTF-8 support (if needed).
If the schema doesn’t enforce UTF-8, alter the column:
ALTER TABLE your_table ALTER COLUMN your_column TYPE text USING your_column::text;Then cast to UTF-8:ALTER TABLE your_table ALTER COLUMN your_column TYPE varchar(255) USING your_column::varchar;(Replace column types as needed.)
Common Mistakes
- Overlooking legacy encodings. Many systems default to ISO-8859-1 or Windows-1252, which lacks characters like non-Latin scripts or emojis. Always verify
client_encodingis UTF-8. - Skipping data validation. Copy-pasting unchecked text (e.g., from Word docs) can introduce corrupt bytes. Use tools like
file -i(Linux) to check file encodings. - Assuming UTF-8 fixes everything. UTF-8 is flexible but requires proper handling of surrogate pairs (UTF-16 sequences like
e28080). Escape such characters or use regex. - Ignoring connection defaults. Some ORMs or client libraries use deprecated encodings. Check the docs for explicit UTF-8 support (e.g.,
pg2in Django).
Tips
- Use
pg_dumpcarefully. Dump with--encoding=UTF8but test the output before reloading. - Test with minimal data. Insert a single malformed string to isolate the issue before full migrations.
- Monitor the console. PostgreSQL logs often reveal the exact byte sequence causing the error (e.g.,
ERROR: invalid byte sequence for encoding...). - Consider application-level fixes. For CSV exports, use
--encoding=UTF-8in tools likecsvkitorlibreoffice.
Troubleshooting
-
The error persists after updating encodings.
Check for hidden control characters. Use a hex editor (e.g., HxD) to scan the string for
00,0A, or0Dbytes. Replace them with spaces or null bytes:sed -i 's/\x0a//g' file.txt(Linux; use Notepad++ for Windows with regex.) -
You’re reading from a legacy database (e.g., MySQL or SQLite) via PostgreSQL.
Convert the data first. Use tools like
pgloaderorsql2jsonto export/import in UTF-8. Example:pgloader mysql://user@host/db --outdir=/tmp --encoding=UTF8 -
You’re using a GUI tool (e.g., Tableau, pgAdmin) and get the error.
Export the query. Run the problematic query through a terminal-based client (like
psql) to avoid encoding issues in the UI. - The error appears after an update. Revert to a known-working version. If the issue started post-update, check the changelog for encoding-related changes. Test with a temporary connection to the old version.
-
You’re working with emojis or non-Latin scripts and still see errors.
Escape surrogate pairs. Replace UTF-16 surrogate pairs (e.g.,
0xD800–0xDFFF) with a placeholder like[U+200D](zero width space). Use a library likeunidecode(Python) oriconvto normalize text. -
The database logs show
22021but you’re not sure where it’s coming from. Check application logs. The error may originate from a client library (e.g.,psycopg2cache) or a misconfigured ORM. Restart the application to clear cached connections.
Frequently Asked Questions
How do I fix a corrupted table caused by this error?
Backup the table first. Use a transaction to drop and recreate it with UTF-8 support:
BEGIN; DROP TABLE your_table; CREATE TABLE your_table (id SERIAL, column_name VARCHAR(255)); INSERT INTO your_table (column_name) SELECT column_name FROM your_table; COMMIT;
Why does my CSV file keep causing this error?
CSVs often use legacy encodings (e.g., windows-1252) for non-Latin text. Convert it to UTF-8 before importing:
iconv -f windows-1252 -t UTF-8 input.csv -o output.csv
Can I force PostgreSQL to accept non-UTF-8 data?
No. PostgreSQL enforces its encoding strictly. If you need legacy support, consider:
- Adding a validation step in your application to reject non-UTF-8 data.
- Using a different database back-end (e.g., MySQL with its own encoding rules).
How do I debug a character I can’t see?
Use a hex editor or Python’s repr():
print(repr("your_string_here"))
This reveals control characters (e.g., \x0a for newline). Or run:
python -c "print(''.join(chr(x) for x in [0x200d]))"
to see a zero-width space.
Why does my emoji lookup query fail?
Emojis require surrogate pairs (UTF-16). Ensure your database column type supports Unicode:
ALTER TABLE your_table ALTER COLUMN emoji_col TEXT;
Then cast to UTF-8:
ALTER TABLE your_table ALTER COLUMN emoji_col TYPE VARCHAR(50) USING emoji_col::varchar;
Is there a way to bypass this for bulk imports?
Yes, but it’s risky. For one-time imports, use:
COPY your_table (column) FROM '/path/to/file' WITH (FORMAT CSV, DELIMITER ',');
Specify UTF-8 explicitly:
COPY ... (ENCODING 'UTF8');
For repeated issues, profile the data source first (e.g., check for BOM markers in files).