Symptoms
COPY input does not match the expected format.
- The error is written to the server log and returned to the client carrying
SQLSTATE 22P04. - Any driver (libpq, JDBC, psycopg, npgsql, pgx) surfaces this code in its error object so you can branch on it programmatically.
- PL/pgSQL can trap it by name:
EXCEPTION WHEN bad_copy_file_format THEN.
Environment
Severity: ERROR | PostgreSQL versions: 12, 13, 14, 15, 16, 17
Reproduce with the exact statement and read the full message in the server log (raise log_min_messages / set log_min_error_statement for more context).
Root Cause
The data stream did not conform to the COPY format, delimiter, quoting, or column count.
Common causes:
- Wrong delimiter, quote, or escape character.
- A column-count mismatch between data and target list.
- Missing header handling, or wrong encoding/line endings.
- CSV versus text mode mismatch.
Diagnostic Queries
Recovery
Steps to resolve 22P04:
- Match the
COPYoptions exactly (FORMAT csv, HEADER true, and the correct DELIMITER, QUOTE, and ESCAPE characters). - Ensure every row has the same number of columns as the target list.
- Set the correct
ENCODINGand line endings. - Validate a few sample rows with a strict parser before the bulk load.
Reference: PostgreSQL error codes — Class 22 (Data Exception).
Thanks — noted. This helps keep the database accurate.