Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

To ignore duplicate keys during 'copy from' in postgresql

Tags:

sql

postgresql

I have to dump large amount of data from file to a table PostgreSQL. I know it does not support 'Ignore' 'replace' etc as done in MySql. Almost all posts regarding this in the web suggested the same thing like dumping the data to a temp table and then do a 'insert ... select ... where not exists...'.

This will not help in one case, where the file data itself contained duplicate primary keys. Any body have an idea on how to handle this in PostgreSQL?

P.S. I am doing this from a java program, if it helps

like image 375
Kam Avatar asked Dec 19 '12 07:12

Kam


People also ask

Does Postgres copy overwrite?

If you COPY data into a table already containing data, the new data will be appended. If you COPY TO a file already containing data, the existing data will be overwritten.

Which key does not allow duplicate values?

You can define keys which allow duplicate values. However, do not allow duplicates on primary keys as the value of a record's primary key must be unique. When you use duplicate keys, be aware that there is a limit on the number of times you can specify the same value for an individual key.


1 Answers

Use the same approach as you described, but DELETE (or group, or modify ...) duplicate PK in the temp table before loading to the main table.

Something like:

CREATE TEMP TABLE tmp_table  ON COMMIT DROP AS SELECT *  FROM main_table WITH NO DATA;  COPY tmp_table FROM 'full/file/name/here';  INSERT INTO main_table SELECT DISTINCT ON (PK_field) * FROM tmp_table ORDER BY (some_fields) 

Details: CREATE TABLE AS, COPY, DISTINCT ON

like image 138
Ihor Romanchenko Avatar answered Oct 05 '22 11:10

Ihor Romanchenko