Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~5 min readSQL
#PostgreSQL#Encoding#COPY#Data Import
A Postgres COPY gate rejecting a file with NUL bytes, a cyan UTF-16 card and an amber bytea column crate

Introduction & Quick Summary

text
ERROR: invalid byte sequence for encoding "UTF8": 0x00 CONTEXT: COPY events, line 4821, column payload

Postgres 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 errorMeaningTypical source
0x00NUL byteUTF-16, fixed-width padding
0xff 0xfeUTF-16 LE BOMWindows "Unicode text" export
0x92CP1252 right quoteExcel CSV on Windows
0xe9Latin-1 éISO-8859-1 export
0xc3 at end of fileTruncated UTF-8Interrupted copy
0xed 0xa0 0x80UTF-8 encoded surrogateBroken 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:

bash
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 payload

Confirm the file contains a NUL before changing any database setting:

bash
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:

bash
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:

bash
iconv -f UTF-16LE -t UTF-8 raw.csv > utf8.csv

Check the result before loading, since iconv fails loudly only when told to:

bash
iconv -f UTF-16LE -t UTF-8 raw.csv > utf8.csv || echo "conversion failed"

Key Comparison Table

Source problemReliable fixLoses data
NUL padding in text columnsStrip \x00Only the padding
UTF-16 fileiconv -f UTF-16 -t UTF-8No
CP1252 quotesiconv -f WINDOWS-1252 -t UTF-8No
Mixed encodings per rowPer-row conversion in a scriptNo
Binary payload in text columnStore as bytea with hexNo
Truncated multi-byte tailTrim the partial last lineYes, the fragment
Load methodHandles encodingHandles NULNotes
COPY ... FROMYes, via client_encodingNoFastest
\copyYesNoClient-side file read
COPY ... FROM PROGRAM 'iconv ...'Yes, server-sideAfter conversionNeeds server access
INSERT from applicationDepends on driverNoSlowest
Staging table + cleanupYesNoLets you inspect rejects

Practical Edge Cases, Error Fixes & Deep Dive Code Examples

Case 1: A UTF-16 CSV exported from Excel

bash
file report.csv # report.csv: Unicode text, UTF-16, little-endian, with BOM

Reading 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:

bash
iconv -f UTF-16 -t UTF-8 report.csv > report.utf8.csv wc -c report.csv report.utf8.csv

The 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

text
ERROR: invalid byte sequence for encoding "UTF8": 0x92

0x92 is the CP1252 right single quote. Either convert the file:

bash
iconv -f WINDOWS-1252 -t UTF-8 export.csv > export.utf8.csv

or tell Postgres the truth about the bytes for that session:

sql
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

text
ERROR: invalid byte sequence for encoding "UTF8": 0xff

A column holding image bytes, a compressed blob or a raw hash cannot be text. Load it as bytea using \x hex in CSV:

python
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 HEADER

bytea 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:

python
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:

bash
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]) PY

A 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:

sql
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_encoding to 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' turns café into caf and is not reversible. Convert encodings; do not delete characters.
  • PostgreSQL 17 ON_ERROR. The option lets COPY skip 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 use ON_ERROR for the remaining row-level problems.
  • SQL_ASCII databases. A database created with SQL_ASCII accepts 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 with SQL_ASCII.
  • pg_dump encoding options. pg_dump --encoding=UTF8 converts on the way out; dumping from a LATIN1 database without it produces files that fail on import into UTF-8. Check with file -bi on 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 documentation

The SQL documentation that defines the behaviour this guide explains.

Try matching browser tools

All tools

Small utilities that fit SQL work — they run entirely in this browser tab, so nothing you paste leaves your device.

All SQL guides

More in SQL

All SQL guides

The guides filed next to this one in SQL, in library order.