bad copy file format
SQLSTATE 22P04 is raised when a file or data stream provided to the COPY command has a format that does not match the specified format options — for example, wrong number of columns, malformed CSV, or missing headers.
- 1COPY CSV file has a different number of columns than the target table or column list
- 2COPY text format uses unexpected delimiter or line endings
- 3Binary COPY file has an invalid header or signature
- 4CSV file has unmatched quote characters or embedded newlines not properly quoted
COPY from a CSV file with mismatched column count.
COPY employees (id, name, department) FROM '/tmp/data.csv' WITH (FORMAT CSV); -- data.csv has only 2 columns but 3 are expected
expected output
ERROR: extra data after last expected column
Fix 1
Match the column list in the COPY command to the actual file structure
WHEN When the file has fewer or more columns than the table.
-- If file has only id and name: COPY employees (id, name) FROM '/tmp/data.csv' WITH (FORMAT CSV);
Why this works
Explicitly listing columns in the COPY command tells Postgres which table columns correspond to the file columns.
Fix 2
Inspect the file format options
WHEN When the format error is about delimiters or quoting.
COPY employees FROM '/tmp/data.csv' WITH (FORMAT CSV, DELIMITER ',', QUOTE '"', HEADER true);
Why this works
Specifying DELIMITER, QUOTE, and HEADER explicitly ensures the COPY parser matches the actual file format.
Class 22 — Data Exception (Postgres-specific)
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev