Migrations

PostgreSQL ERROR: invalid byte sequence for encoding "UTF8"

A CSV import stops at line 18 342, a restore into a new UTF8 database fails halfway, or the application throws it once a week. The cause is almost always the same: bytes that claim to be UTF-8 and are not. Here is how to find them, the right fix for each source, and how to avoid losing hours on a huge load.

· 13 min read · AG Data Team

ERROR: invalid byte sequence for encoding "UTF8" means PostgreSQL received bytes that are supposed to be UTF-8 but do not form a valid UTF-8 character. PostgreSQL validates every string coming in, so the bad bytes never reach the table: the whole statement, or the whole COPY, fails instead.

app=> \copy customers FROM 'customers.csv' WITH (FORMAT csv, HEADER true)
ERROR:  invalid byte sequence for encoding "UTF8": 0xe9 0x20 0x4d
CONTEXT:  COPY customers, line 18342

-- the same family, other variants you may see
ERROR:  invalid byte sequence for encoding "UTF8": 0x00
ERROR:  character with byte sequence 0xe2 0x82 0xac in encoding "UTF8"
        has no equivalent in encoding "LATIN1"

The SQLSTATE is 22021, character_not_in_repertoire in the error codes table. Its sibling 22P05, untranslatable_character, is the has no equivalent in encoding message: the bytes are valid, but the character cannot be converted into the other side's encoding, here a euro sign into LATIN1.

Reading the bytes in the message

The hex values are the start of the offending sequence. In mbutils.c PostgreSQL prints up to 8 bytes, as many as the character should have had. They usually tell you the source straight away:

The four usual sources

  1. A file in the wrong encoding. Spreadsheet exports and older Windows systems often produce Windows-1252. The COPY documentation says input is interpreted according to the ENCODING option or, without it, the current client encoding. Tell PostgreSQL the truth with ENCODING 'WIN1252' and it converts the data for you.
  2. A client that declares the wrong encoding. The session says client_encoding is UTF8, but the terminal or program sends something else. Fix the session with SET client_encoding, \encoding in psql or the PGCLIENTENCODING environment variable, all described in the character set support chapter.
  3. NUL bytes. No setting helps; text cannot hold them. Strip them from the file, or store that column as bytea if the bytes really matter.
  4. A legacy SQL_ASCII database. The documentation is blunt: with SQL_ASCII the server does no conversion and no validation for bytes above 127, which makes it "a declaration of ignorance about the encoding". Such a database can hold UTF-8, Windows-1252 and garbage side by side for years, and the error appears only when you restore it into a UTF8 database. Encoding surprises like this are also a classic stop in a MySQL to PostgreSQL migration, where exported data rarely matches the encoding everyone assumed.
-- 1. the file is really Windows-1252 (Excel, old Windows systems): say so
\copy customers FROM 'customers.csv' WITH (FORMAT csv, HEADER true, ENCODING 'WIN1252')

-- 2. the client lies about its encoding: fix the session, not the data
SHOW client_encoding;
SET client_encoding = 'WIN1252';     -- or in psql: \encoding WIN1252
                                     -- or before connecting: PGCLIENTENCODING=WIN1252

-- 3. convert a value you already hold as bytes
SELECT convert_from('\x436166e9'::bytea, 'WIN1252');   -- 'Café'

WIN1252 and LATIN1 are not the same. They differ in the bytes 0x80 to 0x9F, where Windows-1252 has the euro sign, curly quotes and dashes, and Latin-1 has invisible control characters. Load an Excel export as LATIN1 and it may succeed, quietly turning every euro sign and quote into a control character. When in doubt, look at what those bytes become in a few sample rows.

Finding the bad lines

The CONTEXT line gives you the first failing line number of a COPY, but only the first. On a file with thousands of bad lines, fixing them one error at a time is hopeless. Scan the whole file instead:

# does the file contain invalid UTF-8? (exit code 1 and a byte offset if so)
iconv -f UTF-8 -t UTF-8 customers.csv -o /dev/null

# which lines? invalid UTF-8 or NUL bytes, by line number
perl -ne 'my $c = $_; print "$.\n" if !utf8::decode($c) || /\x00/' customers.csv

# GNU grep alternative for invalid UTF-8 only
LC_ALL=C.UTF-8 grep -naxv '.*' customers.csv

If the file is consistently in one encoding, convert it once with iconv. If it is a mix, which is common with data merged from several systems, converting everything with one source encoding breaks the lines that were already UTF-8. Split out the bad lines, fix them separately and load them after the rest. Avoid iconv -c as a fix: it silently drops the characters it cannot convert, so names and addresses lose letters without any error.

# convert a whole file that is consistently Windows-1252
iconv -f WINDOWS-1252 -t UTF-8 customers.csv -o customers.utf8.csv

# remove NUL bytes (text columns cannot store them)
tr -d '\000' < export.csv > export.clean.csv

What changes on large imports

On a small file the error costs a minute. On a 200 GB export or a multi-terabyte migration, an encoding error late in the load can cost the whole night, and some of the defaults work against you.

# validate the whole file in one streaming pass before loading anything
iconv -f UTF-8 -t UTF-8 big_export.csv -o /dev/null && echo OK

# split into chunks and load each in its own transaction
split -l 5000000 -d --additional-suffix=.csv big_export.csv part_
for f in part_*.csv; do
  psql -v ON_ERROR_STOP=1 -c "\copy events FROM '$f' WITH (FORMAT csv)" \
    && echo "$f" >> loaded.txt || echo "$f" >> failed.txt
done

# before moving a SQL_ASCII database to UTF8: scan each table's data
pg_dump -t public.customers --data-only legacy_db | iconv -f UTF-8 -t UTF-8 -o /dev/null

Key takeaways

PostgreSQL Errors Migrations Data loading
Work with us

Stuck on a migration full of broken characters?

We move legacy and SQL_ASCII databases to clean UTF8, validate the data before cutover and load large datasets without failed overnight imports.

Get in touch More from the blog