Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

PostgreSQL Error 22P04: Fix Bad Copy File Format

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

PostgreSQL error 22P04 occurs when the COPY command encounters malformed data in a file being imported or exported, typically due to mismatched delimiters, missing fields, or incorrect line endings. This error stops the operation immediately and requires manual correction of the source file before retrying. The fix is not a server configuration issue—it’s a data integrity problem that must be resolved at the file level.

What You'll Need

  • A text editor capable of showing hidden characters (like Notepad++, VS Code, or Sublime Text)
  • Access to the PostgreSQL server and the target table structure
  • The original file that triggered the error (CSV, TSV, or custom-delimited)
  • Knowledge of the table's column count, data types, and expected delimiter (usually tab or comma)

Step-by-Step

  1. Identify the exact line number where the error occurred. PostgreSQL reports this in the error message, for example: ERROR: bad copy file format (line 245, column 3). Note the line and column number exactly.
  2. Open the file in a text editor that displays invisible characters. In Notepad++, enable View > Show Symbol > Show All Characters. In VS Code, use View > Toggle Render Whitespace. This reveals tabs, spaces, carriage returns, and line feeds.
  3. Go to the reported line number. Look at the column indicated in the error. If the error is on column 3, count the delimiters (tabs or commas) from the start of the line—column 3 is the third field between delimiters.
  4. Check for missing fields. If your table has 6 columns but the line has only 5 values, the COPY command fails. Add a delimiter with no content (e.g., value1,value2,,value4,value5,value6) to represent the empty field.
  5. Check for unescaped delimiters within data. If a field contains a comma (e.g., San Francisco, CA) and you’re using comma as a delimiter, the field must be wrapped in double quotes: "San Francisco, CA". Without quotes, PostgreSQL treats the comma as a field separator and misaligns columns.
  6. Verify line endings. Files from Windows use CRLF (\r\n), while Unix/Linux use LF (\n). PostgreSQL expects LF. Use your editor to convert line endings to Unix format (in Notepad++, use Edit > EOL Conversion > Unix (LF)).
  7. Confirm the delimiter matches the COPY command. If you used COPY table FROM 'file.csv' WITH CSV, the file must use commas. If you used WITH DELIMITER '\t', the file must use tabs. Mismatched delimiters cause field misalignment.
  8. Remove any header row if the COPY command does not include HEADER. If the first line contains column names and you didn’t specify HEADER, PostgreSQL tries to insert those names as data, causing a type mismatch or count error.
  9. Ensure no trailing delimiter exists at the end of any line. For example, value1,value2, has an extra comma at the end—this creates an empty 3rd field where none was intended, breaking column count.
  10. Save the corrected file with the same name or a new name, then retry the COPY command exactly as before.

Common Mistakes

  • Assuming the file is correct because it opened fine in Excel—Excel hides delimiters and auto-corrects formatting, masking the real issue.
  • Using a spreadsheet to export without selecting the correct delimiter or quote options—Excel exports may use incorrect line endings or unquoted embedded commas.
  • Ignoring the column number in the error message and only checking the line. The column tells you exactly which field is malformed.
  • Trying to fix the error by changing PostgreSQL settings like standard_conforming_strings—this error is always data-related, never a server setting.
  • Copying data from a web page or PDF without cleaning invisible Unicode characters or non-breaking spaces—these can appear as normal spaces but are invalid in COPY.

Tips

  • Use COPY table TO 'file.csv' WITH CSV HEADER to export a clean template from an existing table, then populate it—this ensures the format matches exactly.
  • For large files, test with the first 100 lines using a smaller sample before running the full import.
  • Use the psql meta-command \copy instead of COPY when importing from a local file—it runs on the client side and avoids permission issues with server file paths.
  • Always validate your data types: if a column is INTEGER and the file has abc in that field, you’ll get a type conversion error, not 22P04. Error 22P04 is strictly about structure, not content.
  • When in doubt, open the file in a hex editor to spot non-printable characters like \x00 (null bytes) or \x1A (substitute characters) that cause silent corruption.

Troubleshooting

If the error persists after correcting the file:

  1. Verify the table structure matches the file. Run \d table_name in psql to list columns and data types. Ensure the number of columns in the file equals the number of columns in the table.
  2. Test with a minimal file: create a new file with just two rows—one header (if using HEADER), one data row with all field types you’re using. If this works, the issue is in the bulk data.
  3. Check for encoding issues. If the file uses UTF-16 or ISO-8859-1 but PostgreSQL expects UTF-8, use COPY ... WITH (FORMAT csv, ENCODING 'UTF8'). If unsure, re-save the file as UTF-8 in your text editor.
  4. If the file was generated by a third-party tool (like Excel, Python, or a legacy system), re-export it using a different tool. For example, export from Excel as "CSV UTF-8 (Comma delimited)" instead of standard CSV.
  5. Use head -n 250 filename (Linux/macOS) or Get-Content filename -TotalCount 250 (PowerShell) to preview the problematic area without opening the full file.
  6. If the file is extremely large (GBs), use a script to validate each line. A Python script using csv.reader() can catch malformed rows without loading everything into memory.

Frequently Asked Questions

Why does PostgreSQL say "bad copy file format" when my file looks fine in Excel?

Excel hides delimiters, auto-corrects line endings, and may insert invisible characters. The file may have mixed delimiters, unquoted commas in text fields, or Windows CRLF endings that PostgreSQL rejects.

Can I fix this error by changing the PostgreSQL configuration?

No. Error 22P04 is caused by malformed input data, not server settings. No configuration change will bypass a structural data error.

What if my data has literal backslashes or quotes?

Escape them properly. Use double quotes around fields containing quotes, and escape internal quotes with another quote (e.g., "She said \"Hello\""). For backslashes, use two backslashes if the format requires escaping.

Does the file need to be on the server?

Only if using the server-side COPY command. Use \copy in psql to import from your local machine without requiring server file access.

Why does the error point to column 3 when the line seems to have 5 values?

Unquoted embedded delimiters break field parsing. For example, 1,John Doe,New York, NY,30 has a comma in "New York, NY". Without quotes, PostgreSQL sees six fields, not five, causing misalignment.

Can I automate validation before importing?

Yes. Use Python’s csv module to read the file and catch row count or delimiter mismatches before sending to PostgreSQL. Or use awk to count delimiters per line and flag inconsistencies.