最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How can I ignore errors when copy one table to another in postgresql? - Stack Overflow

programmeradmin2浏览0评论

I am using Postgresql 15. I have two tables with example table structure. The table mytable has many data but the other table mycopy is empty. The mycopy table has an extra unique constrain on one column. I want to copy all data from mytable to mycopy table. But the data in mytable has duplicate value on the unique constrain column for mycopy table. How can I copy the data but skip those duplicate rows based on that column? But below statement will stop if there is a constrain error during insert.

INSERT INTO mycopy
SELECT * FROM mytable;

I am using Postgresql 15. I have two tables with example table structure. The table mytable has many data but the other table mycopy is empty. The mycopy table has an extra unique constrain on one column. I want to copy all data from mytable to mycopy table. But the data in mytable has duplicate value on the unique constrain column for mycopy table. How can I copy the data but skip those duplicate rows based on that column? But below statement will stop if there is a constrain error during insert.

INSERT INTO mycopy
SELECT * FROM mytable;
Share Improve this question asked Feb 7 at 23:34 Joey Yi ZhaoJoey Yi Zhao 42.5k87 gold badges349 silver badges654 bronze badges 4
  • 1 So just SELECT DISTINCT ON (the_column) * FROM mytable? – Bergi Commented Feb 7 at 23:39
  • How do you know which duplicate you want to eliminate? – Adrian Klaver Commented Feb 7 at 23:42
  • I don't mind which one get eliminated. – Joey Yi Zhao Commented Feb 8 at 2:13
  • 2 Add ON CONFLICT DO NOTHING to the INSERT. Also, explicitly listing the columns is strongly recommended. – JohnH Commented Feb 8 at 2:48
Add a comment  | 

1 Answer 1

Reset to default 2

The following will skip rows that violate unique key constraints:

INSERT INTO mycopy -- should list columns here and in the SELECT
SELECT * FROM mytable
ON CONFLICT DO NOTHING;

Refer to the PostgreSQL Documentation for additional details.

As the comment states, columns should be listed. Doing so protects against potential mismatched columns.

发布评论

评论列表(0)

  1. 暂无评论