やりたいこと
bigint generated by default as identity primary key で作成した id をリセットする。
以下のテーブルにレコードを登録した後、レコード削除後に id が 1 から始まるようにする。
id bigint generated by default as identity primary key
name varchar(32)
delete ではなく、truncate table {テーブル名} restart identity でレコードを削除することで、レコード削除後に id が 1 から始まるようになる。
動作検証
テーブル作成後にレコードを登録
テーブル作成
create table test_id (
id bigint generated by default as identity primary key,
name varchar(32)
);
登録
insert into test_id (name) values ('aaa');
insert into test_id (name) values ('bbb');
insert into test_id (name) values ('ccc');
確認
select * from test_id order by id asc;
id | name
----+------
1 | aaa
2 | bbb
3 | ccc
delete でのレコード削除にレコードを登録
削除
delete from test_id;
delete 後にレコードを登録する。
登録
insert into test_id (name) values ('aaa');
insert into test_id (name) values ('bbb');
insert into test_id (name) values ('ccc');
確認
select * from test_id order by id asc;
id | name
----+------
4 | aaa
5 | bbb
6 | ccc
delete でテーブルを空にしてレコードを登録しても id は 1 に戻らない
truncate ... restart identity でのレコード削除後にレコードを登録
削除
truncate table test_id restart identity;
確認
select * from test_id order by id asc;
id | name
----+------
全レコードを削除した後、新たにレコードを登録する。
登録
insert into test_id (name) values ('aaa');
insert into test_id (name) values ('bbb');
insert into test_id (name) values ('ccc');
確認
select * from test_id order by id asc;
id | name
----+------
1 | aaa
2 | bbb
3 | ccc
truncate でのレコード削除後に、id が 1 から始まることが確認できた。