Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape commas inside CSV values when importing table to PostgreSQL?

I am trying to use the 'copy' command for importing the csv file into my postgres table. Values containing commas have been surrounded by double quotes but I can't seem to find an option to load them into the postgres table without any errors using the 'copy' command.

'COPY' command I am using:

CREATE TABLE candidates (Sno int, name varchar, cases int, case_details varchar, .....);
copy candidates from 'something.csv' with NULL AS ' ' csv ;

Example of an offending csv line:

1, "some name", 2, "(1):IPC Sections -  147, 323, 352, 504, 506 , Other Details - Case no.283A/2000, A.C.J.M-5, Ghumangunj Ellahabad, UP, Dt.12.11.2000", .....

Above the case_details attribute has commas in its value. That is my problem.

like image 284
kb_14 Avatar asked Oct 28 '25 07:10

kb_14


1 Answers

Works for me (PG 9.2, linux):

$ cat something.csv 
1, "some name", 2, "(1):IPC Sections -  147, 323, 352, 504, 506 , Other Details - Case no.283A/2000, A.C.J.M-5, Ghumangunj Ellahabad, UP, Dt.12.11.2000"

$ psql test
test=> CREATE TABLE candidates (Sno int, name varchar, cases int, case_details varchar);
CREATE TABLE
test=> \copy candidates from 'something.csv' with NULL AS ' ' csv ;
test=> select * from candidates ;
 sno |    name    | cases |                                                             case_details                                                             
-----+------------+-------+--------------------------------------------------------------------------------------------------------------------------------------
   1 |  some name |     2 |  (1):IPC Sections -  147, 323, 352, 504, 506 , Other Details - Case no.283A/2000, A.C.J.M-5, Ghumangunj Ellahabad, UP, Dt.12.11.2000
(1 row)
like image 114
sega_sai Avatar answered Oct 30 '25 23:10

sega_sai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!