Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Fix PostgreSQL Error 22021: Invalid Character in String

· 5 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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

  1. 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 shows e28080, it’s likely a surrogate character (e.g., from malformed UTF-8).
  2. Check your database encoding. Run: SELECT setting FROM pg_settings WHERE name = 'client_encoding'; If it returns S-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 via SELECT pg_reload_conf();).
  3. Fix the data source (if applicable).
    1. For file imports: Ensure the file is properly encoded with UTF-8. Use: iconv -f -t UTF-8 input.csv > output.csv (Replace source_encoding with the actual encoding, e.g., windows-1252.)
    2. 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.)
  4. 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]);
  5. 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_encoding is 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., pg2 in Django).

Tips

  • Use pg_dump carefully. Dump with --encoding=UTF8 but 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-8 in tools like csvkit or libreoffice.

Troubleshooting

  1. 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, or 0D bytes. Replace them with spaces or null bytes: sed -i 's/\x0a//g' file.txt (Linux; use Notepad++ for Windows with regex.)
  2. You’re reading from a legacy database (e.g., MySQL or SQLite) via PostgreSQL. Convert the data first. Use tools like pgloader or sql2json to export/import in UTF-8. Example: pgloader mysql://user@host/db --outdir=/tmp --encoding=UTF8
  3. 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.
  4. 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.
  5. 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 like unidecode (Python) or iconv to normalize text.
  6. The database logs show 22021 but you’re not sure where it’s coming from. Check application logs. The error may originate from a client library (e.g., psycopg2 cache) 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).