LoginSignup
1
2

More than 1 year has passed since last update.

(PostgreSQL)updated_at を自動更新する

Posted at

前提

このようにテーブルに1行レコードが挿入されているとする。

テーブル名:test_automatic_updating

id name created_at updated_at
1 makima 2023 06:50:20 2023 06:50:20

やり方

①関数を定義
②トリガーを定義

①関数を定義
CREATE FUNCTION update_test_automatic_updating_updated_at()
RETURNS TRIGGER AS $$
BEGIN
  NEW.updated_at = now();
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;
②トリガーを定義
CREATE TRIGGER update_test_automatic_updating
BEFORE UPDATE ON test_automatic_updating
FOR EACH ROW
EXECUTE FUNCTION update_test_automatic_updating_updated_at();

テーブルを更新

-- 名前だけ変更
UPDATE test_automatic_updating SET name = 'shihainoakuma' ;

結果、update_atの値も更新してくれている

id name created_at updated_at
1 shihainoakuma 2023 06:50:20 2023 07:00:21
1
2
0

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
1
2