LoginSignup
24
21

More than 5 years have passed since last update.

PostgreSQLでCSVからUpdateをかける

Posted at

insertの場合は\copyコマンドを使えばいいのだが、updateの場合はそうはいかないみたい。

↑のstack overflowの回答にある通り、

やり方

  1. updateしたいCSVデータを一旦tmpテーブルを作成しそこにインポート
  2. tmpデータのデータでUpdateしたいテーブルにupdateをかける

例えば以下のようにする。

-- Create tmp table (セッション内のみ有効なテーブル):
create temp table tmp (id int, issuedate__c datetime)

-- Import data from csv:
\copy tmp from '/path/to/file.csv' with null '' csv;

-- Update table from tmp
update
    "users"
set
    id = tmp.id,
    created_at = tmp.created_at
where
    "users".id = tmp.id

-- これはやらなくてもセッションが切れたと時に自動で削除される
drop table tmp;

!注意!

ここで注意なのが、アップデートかけたいレコード数が巨大な場合、temp_buffersの値を大きくし、tmpテーブルにインデックスを張らないと処理落ちしてしまう、とのこと。

-- Set temp_buffer:
SET temp_buffers = 500MB;  -- example value

-- Add index to the temporary table:
CREATE INDEX tmp_id_idx ON tmp(id);

-- Analyze indexes info
ANALYZE tmp;
24
21
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
24
21