
Loading a CSV Into a Staging Table Then Cleaning It in SQL
Load a messy CSV as text first, then convert it with SQL. Build a three format date parser, a reject table with reasons, and the typed insert.
Tag
44 posts

Load a messy CSV as text first, then convert it with SQL. Build a three format date parser, a reject table with reasons, and the typed insert.

COPY cannot skip file columns. Compare two ways to load three of eight columns of a 2,000,000 row CSV, with timings, and see why cut breaks on quotes.

COPY stops with an invalid byte sequence error when a CSV is Latin 1. Fix it with the ENCODING option or client_encoding, and avoid the SQL_ASCII trap.

The COPY error means a row has more fields than the table has columns. See the four usual causes, how to find the line, and the fix for each one.

Skip the header, or better, check it. See what HEADER true, HEADER match and a column list do, and the errors when the file and the table disagree.

The two commands differ in which machine reads the file. See the permission errors, the path errors and the timings, and choose the one that fits.

The COPY command in practice: the options that matter, the two ways to feed it, what its row count means, and why one bad value undoes the whole load.

Load a CSV into PostgreSQL with COPY, see what makes it fast, and learn what each failure means, with a script that loads in one transaction.