SQLSTATE 22021Severity mediumLab verified

Incident brief

Invalid byte sequence for encoding

Interpreting bytes as text in a given encoding fails when the bytes are not valid there; 0xff is never a valid standalone UTF-8 byte.

Reproduced on PostgreSQL 18.4Verified 2026-07-24 (isolated lab, PostgreSQL 18.4)Reviewed by Verified against PostgreSQL 18.4 in an isolated lab environment

In 10 seconds

What
Invalid byte sequence for encoding
What triggers it
Call convert_from(bytea, encoding) where the bytes are not valid in the stated encoding.
The fix
Feed bytes that are actually valid in the declared encoding.
Proof
Reproduced on PostgreSQL 18.4 → A single SELECT reproduces SQLSTATE 22021; the byte 0xff is rejected as invalid UTF-8.

The fix

What to do right now

The immediate, application-level response to this error.

  • Feed bytes that are actually valid in the declared encoding.
  • If the true encoding differs, decode with the correct one (for example LATIN1) instead of UTF8, or sanitize the input first.
Fix — SQL
-- Decode only bytes that are valid in the target encoding.
SELECT convert_from('\x41'::bytea, 'UTF8');

Related & next steps

Follow the thread

Everything this error touches — jump straight to the sibling error, term, runbook, or parameter.

Verification

PG 18.4
Last verified
2026-07-24 (isolated lab, PostgreSQL 18.4)
Reviewed by
Verified against PostgreSQL 18.4 in an isolated lab environment
Audit status
reviewed