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.

What lands in your log

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

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

In 10 seconds

What triggers it
Call convert_from(bytea, encoding) where the bytes are not valid in the stated encoding.
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.

Fix

What to do right now

Application-level steps for 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');

Connected

Everything this error touches

Every page this SQLSTATE connects to: the concept that explains it, the runbooks that fix it, the parameters you tune to prevent it, and the sibling errors it travels with. All real cross-references. Jump straight in, or open the full interactive map.

Open in the interactive map →

Verification

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

Went further?

Pro unlocks the second lab proof

Free page stops the bleeding. Pro adds the operational test, SQLSTATE audit, and deeper evidence, same error, more certainty.

FollowSubstackLinkedInnew errors · lab notes · hiring loops