0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

PostgreSQL で insert、update したレコードのフィールドを取得

0
Posted at

やりたいこと

PostgreSQL でレコードの登録・更新時に変更があったレコードの id を取得する。

データ更新時のレコードの id を取得

insert/update/delete に returning {フィールド} を指定すると、変更があったレコードの情報を取得することができる。

テーブル定義例

create table test1 (
  id    integer generated always as identity primary key,
  name  varchar(32) not null
);

insert into test1 (name) values ('aaa');
insert into test1 (name) values ('bbb');
insert into test1 (name) values ('ccc');

returning による id の取得

insert の場合

insert の場合
insert into test1 ('name') valuse ('ddd'), ('eee') returning id;

 id
----
  4
  5
(2 rows)

# select * from test1 where id in (4, 5);

 id | name
----+------
  4 | ddd
  5 | eee
(2 rows)

update の場合

update
# update test1 set name = 'abc' where name = 'aaa' returning id;

 id
----
  1
(1 row)

# select * from test1 where id = 1;

 id | name
----+------
  1 | abc
(1 row)

returning には , 区切りで複数のフィールドを指定することができる。

# insert into test1 (name) values ('fff'), ('ggg') returning id, name;

 id | name
----+------
  6 | fff
  7 | ggg
(2 rows)

delete の場合

# delete from test1 where name = 'bbb' returning id, name;

 id | name
----+------
  2 | bbb
(1 row)

# select * from test1 order by id asc;

 id | name
----+------
  1 | abc
  3 | ccc
  4 | ddd
  5 | eee
  6 | fff
  7 | ggg
(6 rows)
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?