7

I am trying to import a trivial CSV to Postgres 8.4 database:

Here is a table:

CREATE TABLE public.sample (
  a VARCHAR, 
  b VARCHAR
) WITHOUT OIDS;

Here is a CSV file sample:

"foo","bar, baz"

The query:

COPY sample FROM '/tmp/sample.csv' USING DELIMITERS ',';

Throws an exception:

ERROR:  extra data after last expected column
CONTEXT:  COPY sample, line 1: ""foo","bar, baz""

But, well, CSV parsing is not rocket science and I wonder if it is not possible to solve without reformatting the source CSV file.

Input comes from a 3rd party, I cannot change the format.
(I understand I could pre-process to change the delimiter before I import it.)

Final solution:

COPY sample FROM '/tmp/sample.csv' WITH DELIMITER ',' CSV;

Originally taken from https://stackoverflow.com/a/9682174/251311, and documentation page is http://www.postgresql.org/docs/8.4/static/sql-copy.html

Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
zerkms
  • 249,484
  • 69
  • 436
  • 539

1 Answers1

8

Clearly, you have a CSV file while you try to import it as text format. For Postgres 9.1 or newer, use:

COPY sample FROM '/tmp/sample.csv' (FORMAT csv);

The default delimiter for CSV format is the comma (,) anyway. More in the manual.
For PostgreSQL 8.4 or older:

COPY sample FROM '/tmp/sample.csv' CSV;
Erwin Brandstetter
  • 605,456
  • 145
  • 1,078
  • 1,228
  • 1
    For 8.4 the syntax is slightly different though http://www.postgresql.org/docs/8.4/static/sql-copy.html – zerkms Apr 03 '12 at 21:43
  • @zerkms: Right, the syntax is for the current version 9.1. I added the 8.4 variant for documentation. – Erwin Brandstetter Apr 03 '12 at 21:46
  • Just a quick comment for those who are now on version 10.x - syntax now is more like `COPY sample FROM '/tmp/sample.csv' WITH FORMAT (CSV, DELIMITER ',', NULL ' ');` – PJATX Jan 29 '18 at 23:34