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:
- A single byte from 0x80 to 0xFF followed by plain ASCII, like
0xe9 0x20 0x4dabove: that is "é", a space and "M" in Windows-1252 or Latin-1. The file is not UTF-8 at all, or one part of it is not. 0x00: a NUL byte. It is valid in UTF-8 as a byte, but PostgreSQL text types cannot store it; the encoding checks in wchar.c are required to reject zeroes. It typically comes from binary data dumped into a text export or from UTF-16 files.- A valid lead byte followed by something that does not fit: often a UTF-8 string cut in the middle of a character, for example by an application that truncates by byte length. In our experience this is the usual cause when the error appears only now and then in production.
The four usual sources
- 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
ENCODINGoption or, without it, the current client encoding. Tell PostgreSQL the truth withENCODING 'WIN1252'and it converts the data for you. - A client that declares the wrong encoding. The session says
client_encodingis UTF8, but the terminal or program sends something else. Fix the session withSET client_encoding,\encodingin psql or thePGCLIENTENCODINGenvironment variable, all described in the character set support chapter. - NUL bytes. No setting helps; text cannot hold them. Strip them from the file, or store that column as
byteaif the bytes really matter. - 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.
- One bad byte rolls back the whole COPY. Every row loaded before the failure is thrown away, and on the table those rows remain as dead tuples until vacuum cleans them up. A failure at line 180 million means the work and the disk space for 180 million rows were wasted.
- ON_ERROR ignore does not save you here. PostgreSQL 17 added
ON_ERROR ignoretoCOPY(release notes) and PostgreSQL 18 addedREJECT_LIMIT(release notes). The documentation limits them to errors converting a column's input value into its data type. Encoding validation happens earlier, on the raw input in copyfromparse.c, and raises a normal error, so a single invalid byte still stops the load. - Validate first, in one streaming pass.
iconvto/dev/nullreads the file once without storing anything. It is far cheaper than discovering the problem through a failed load. - Load in chunks. Split huge files and load each chunk in its own transaction, keeping a list of what loaded. A bad chunk then costs one chunk, and you can rerun only the failures.
- Scan SQL_ASCII data before the cutover, not during it. Before moving a large SQL_ASCII database to UTF8, stream each table's data through a validator, ideally from a replica, and fix the rows by primary key while the old system is still live. Dumping a large database covers parallel
pg_dumpruns and dumping from a standby without hurting production;pg_dump -Ecreates the dump in a chosen encoding, as the pg_dump documentation describes. - Fix the source, not just the copy. If an application truncates strings by bytes or a nightly export writes the wrong encoding, the errors will come back with the next batch. In our experience it pays to add the same
iconvcheck to the export job itself.
# 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
- The error means bytes claimed as UTF-8 are not valid UTF-8; PostgreSQL rejects the whole statement or
COPY. - The hex bytes in the message point to the source: single high bytes mean Windows-1252 or Latin-1,
0x00means NUL bytes. - Declare the real encoding with
COPY ... ENCODINGorclient_encoding; do not mix up WIN1252 and LATIN1. - Find all bad lines with
iconvorperlbefore loading; avoidiconv -c, which drops characters silently. ON_ERROR ignoredoes not skip encoding errors, so validate and chunk large loads, and scan SQL_ASCII data before migrating.