Postgres: invalid byte sequence for encoding UTF8 0x00
Postgres text cannot store NUL bytes. The file is UTF-16, fixed-width padded or binary; convert the encoding, strip padding, or load the column as bytea.

Introduction & Quick Summary
ERROR: invalid byte sequence for encoding "UTF8": 0x00
CONTEXT: COPY events, line 4821, column payloadPostgres received bytes it cannot decode as UTF-8. 0x00 is the NUL byte, which UTF-8 permits in theory but Postgres forbids inside text, varchar, char, jsonb and every other text-backed type. The CONTEXT line names the file line and column, which is the whole diagnosis for most incidents.
Where NUL bytes come from:
- UTF-16 files read as UTF-8. Every ASCII character becomes
41 00, so the second byte of the first character is a NUL. - Fixed-width exports. SQL Server
bcp, COBOL extracts and mainframe dumps pad fields with NULs. - Binary columns loaded as text. Images, hashes or protobuf blobs in a CSV column.
- Truncated or corrupted dumps. A partial write cuts a multi-byte character in half.
| Bytes in the error | Meaning | Typical source |
|---|---|---|
0x00 | NUL byte | UTF-16, fixed-width padding |
0xff 0xfe | UTF-16 LE BOM | Windows "Unicode text" export |
0x92 | CP1252 right quote | Excel CSV on Windows |
0xe9 | Latin-1 é | ISO-8859-1 export |
0xc3 at end of file | Truncated UTF-8 | Interrupted copy |
0xed 0xa0 0x80 | UTF-8 encoded surrogate | Broken converter |
Core Mechanics, Signatures & Reproducible Setup
COPY and INSERT decode the client's bytes using the session's client_encoding, convert to the database encoding, and store the result. A decode failure aborts the statement before any row is inserted, and the message reports the first offending byte. The database encoding is fixed at initdb; client_encoding is per session and can be changed.
Reproduce it:
printf 'id,payload\n1,ok\n2,bad\x00value\n' > /tmp/nul.csv
psql -d app -c "\copy events (id, payload) FROM '/tmp/nul.csv' CSV HEADER"
# ERROR: invalid byte sequence for encoding "UTF8": 0x00
# CONTEXT: COPY events, line 3, column payloadConfirm the file contains a NUL before changing any database setting:
grep -c $'\x00' /tmp/nul.csv # count of lines containing NUL
file -bi /tmp/nul.csv # charset=us-ascii or utf-8
python3 -c "
data = open('/tmp/nul.csv','rb').read()
print('nul bytes:', data.count(b'\x00'))
print('first offset:', data.find(b'\x00'))
"Remove them and reload:
python3 -c "
src = open('/tmp/nul.csv','rb').read()
open('/tmp/clean.csv','wb').write(src.replace(b'\x00', b''))
"
psql -d app -c "\copy events (id, payload) FROM '/tmp/clean.csv' CSV HEADER"For a UTF-16 file, conversion is the correct fix rather than deletion, because stripping NULs from UTF-16 leaves interleaved text that decodes to nonsense:
iconv -f UTF-16LE -t UTF-8 raw.csv > utf8.csvCheck the result before loading, since iconv fails loudly only when told to:
iconv -f UTF-16LE -t UTF-8 raw.csv > utf8.csv || echo "conversion failed"Key Comparison Table
| Source problem | Reliable fix | Loses data |
|---|---|---|
| NUL padding in text columns | Strip \x00 | Only the padding |
| UTF-16 file | iconv -f UTF-16 -t UTF-8 | No |
| CP1252 quotes | iconv -f WINDOWS-1252 -t UTF-8 | No |
| Mixed encodings per row | Per-row conversion in a script | No |
| Binary payload in text column | Store as bytea with hex | No |
| Truncated multi-byte tail | Trim the partial last line | Yes, the fragment |
| Load method | Handles encoding | Handles NUL | Notes |
|---|---|---|---|
COPY ... FROM | Yes, via client_encoding | No | Fastest |
\copy | Yes | No | Client-side file read |
COPY ... FROM PROGRAM 'iconv ...' | Yes, server-side | After conversion | Needs server access |
INSERT from application | Depends on driver | No | Slowest |
| Staging table + cleanup | Yes | No | Lets you inspect rejects |
Practical Edge Cases, Error Fixes & Deep Dive Code Examples
Case 1: A UTF-16 CSV exported from Excel
file report.csv
# report.csv: Unicode text, UTF-16, little-endian, with BOMReading it with client_encoding=UTF8 produces the 0x00 error at the first character, because \x00 follows every ASCII byte. Convert once and keep the original:
iconv -f UTF-16 -t UTF-8 report.csv > report.utf8.csv
wc -c report.csv report.utf8.csvThe byte count dropping roughly by half is the confirmation that the conversion ran. If iconv reports illegal input sequence, the file mixes encodings and needs a per-line pass.
Case 2: CP1252 punctuation
ERROR: invalid byte sequence for encoding "UTF8": 0x920x92 is the CP1252 right single quote. Either convert the file:
iconv -f WINDOWS-1252 -t UTF-8 export.csv > export.utf8.csvor tell Postgres the truth about the bytes for that session:
SET client_encoding TO 'WIN1252';
\copy notes (id, body) FROM 'export.csv' CSV HEADER;
RESET client_encoding;Setting client_encoding to match the file is correct and loses nothing; setting it to LATIN1 to "make it work" silently mangles characters that CP1252 maps differently, such as the em dash.
Case 3: Binary data in a text column
ERROR: invalid byte sequence for encoding "UTF8": 0xffA column holding image bytes, a compressed blob or a raw hash cannot be text. Load it as bytea using \x hex in CSV:
import csv, binascii
with open("out.csv", "w", newline="") as f:
w = csv.writer(f)
w.writerow(["id", "blob"])
w.writerow([1, "\\x" + binascii.hexlify(b"\xff\xd8\xff").decode()])CREATE TABLE assets (id int PRIMARY KEY, blob bytea);
\copy assets FROM 'out.csv' CSV HEADERbytea accepts any bytes, including NUL, because it is not a text type. Converting an existing mangled column is a migration, not a load option.
Case 4: jsonb and the NUL escape
INSERT INTO events (payload) VALUES ('{"note": "a\u0000b"}');
-- ERROR: unsupported Unicode escape sequence
-- DETAIL: \u0000 cannot be converted to text.This is SQLSTATE 22P05, not the byte sequence error, but the root cause is the same rule: jsonb cannot store NUL. The json type preserves the escape as text, so a column typed json accepts the document while jsonb rejects it. If the value must be stored, remove or replace the escape in the producer:
import json
doc = {"note": "a\x00b"}
clean = json.loads(json.dumps(doc).replace("\\u0000", ""))Sanitize at the API boundary rather than in the database, because the same string will break any downstream text consumer too.
Case 5: Unknown encoding in a large dump
When iconv cannot decide, inspect the first bytes and the ratio of NULs:
head -c 64 dump.bin | xxd
python3 - <<'PY'
data = open('dump.bin','rb').read(1_000_000)
print('nul ratio', data.count(b'\x00') / len(data))
try:
data.decode('utf-8')
print('valid utf-8 prefix')
except UnicodeDecodeError as e:
print('invalid at', e.start, data[e.start-10:e.start+10])
PYA NUL ratio near 0.5 means UTF-16; a ratio near 0 with sporadic 0x80–0xFF bytes means a single-byte legacy encoding. Guessing and loading is how data gets corrupted quietly; the ratio and a sample of the offending offset settle it in seconds.
Case 6: Cleaning inside the load with COPY FROM PROGRAM
On a server where you control the filesystem, convert in the pipeline:
COPY events (id, payload)
FROM PROGRAM 'iconv -f UTF-16LE -t UTF-8 /srv/import/events.csv | tr -d "\000"'
WITH (FORMAT csv, HEADER true);FROM PROGRAM runs as the Postgres OS user, so the path must be readable by that user and the command must exist on the server. It is convenient for one-off imports and unsuitable for untrusted input, since the program runs with database server privileges.
Common Compilation/Runtime Mistakes & Version Gotchas
- Setting
client_encodingto silence the error. If the file is not actually in that encoding, the data is stored with mojibake and the error disappears. Match the encoding you can verify, not the one that stops the message. - Stripping all high bytes.
tr -d '\200-\377'turnscaféintocafand is not reversible. Convert encodings; do not delete characters. - PostgreSQL 17
ON_ERROR. The option letsCOPYskip rows with data conversion and constraint errors, which is useful for dirty imports, but it does not make an invalid byte sequence valid. Fix the bytes first, then useON_ERRORfor the remaining row-level problems. SQL_ASCIIdatabases. A database created withSQL_ASCIIaccepts any byte, including NUL? No: NUL is rejected even there, but other invalid sequences are stored as-is and fail later when read by a UTF-8 client. Never create new databases withSQL_ASCII.pg_dumpencoding options.pg_dump --encoding=UTF8converts on the way out; dumping from aLATIN1database without it produces files that fail on import into UTF-8. Check withfile -bion the dump.- Drivers that transcode silently. Some MySQL drivers replace invalid characters with
?before Postgres ever sees them, so the corruption appears as data loss with no error. Validate byte length and characters at the boundary, not only at the database.
To inspect the offending row before touching the file, load a few lines into the CSV to JSON converter and look for replacement characters or empty strings. For hex-level inspection of the bytes, the base64 encoder shows the exact sequence without a terminal, and the SQL formatter keeps the staging-table queries readable for review.
Primary references: COPY documents ENCODING, FROM PROGRAM and the ON_ERROR option, and Appendix A lists 22021 (invalid byte sequence) alongside 22P05 for unsupported Unicode escapes.
Official references
primary documentationThe SQL documentation that defines the behaviour this guide explains.
Try matching browser tools
All toolsSmall utilities that fit SQL work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related SQL guides
All SQL guidesSQLite: database is locked (SQLITE_BUSY) under concurrent writes
SQLite allows one writer. Set a busy timeout, switch to WAL, start write transactions as IMMEDIATE, and reduce to a single writer connection.
SQL Window Functions: ROW_NUMBER, RANK, DENSE_RANK, and LEAD/LAG Explained
How the four ranking and offset functions differ on ties, why the default RANGE frame makes running totals repeat, and how LAG builds gap-and-island.
Postgres: column does not exist (SQLSTATE 42703)
42703 means the identifier you wrote is not the one that exists. Check case folding, alias scope, search_path and migration drift.
PostgreSQL: canceling statement due to statement timeout
The statement was canceled by statement_timeout. Find whether the role, the pooler or the client set it, then scope a longer budget to that job.
More in SQL
All SQL guidesThe guides filed next to this one in SQL, in library order.