0

I have a table in Postgres with only 2 columns

CREATE table dummy(col1 char(10), col2 char(10));

The CSV file has the following columns:

gid        prov             name        pop1996
4468       BC              VANCOUVER    514008
4501       BC               SURREY      304477
4473       BC               BURNABY     179209
4485       BC               RICHMOND    148867

How can I copy gid and name only from this file using \COPY?

Nidhi
  • 829
  • 3
  • 8
  • 18
  • 1
    Probably duplicate of http://stackoverflow.com/questions/12618232/copy-a-few-of-the-columns-of-a-csv-file-into-a-table – Jan Marek Apr 21 '16 at 11:59

1 Answers1

-1

If you don't mind creating other tables you can follow the Q/A @Jan Marek pointed out: https://stackoverflow.com/a/12619903/318174

If you can't create additional tables than you can do this:

You will need to preprocess the CSV file first by eliminating the columns you don't want. The easiest way is using UNIX cut.

cat file.csv | cut -d '\t' 1,3 > processed.csv

If your CSV file has some escaping needed you can use a python script I wrote a long time ago that is exactly like cut but respects CSV.

cat file.csv | csvcut.py -d '\t' 1,3 > processed.csv

Next you load up psql and enter:

\copy your_table (col1,col2) FROM '/path/to/processed.csv' DELIMITER '\t' CSV;
Community
  • 1
  • 1
Adam Gent
  • 47,843
  • 23
  • 153
  • 203
  • Python installs on windows so you can use my python script. – Adam Gent Apr 21 '16 at 12:17
  • Oh you will still need to pipe the csv file to the python script. Well I recommend if you haven't already install Powershell, Cygwin, Babun or Gow. Once you do that open the better shell and run the command. – Adam Gent Apr 21 '16 at 12:22
  • Is there a way out, If i don't want to install anything new ? – Nidhi Apr 21 '16 at 12:36
  • Don't actually have to pre-process the file. Can directly copy `FROM PROGRAM 'cat /path/to/file.csv | cut -d '\t' 1,3'` instead. – David Backeus Mar 27 '20 at 17:41