6
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?

More than 3 years have passed since last update.

PostgreSQL: truncate tableするときにシーケンスをリセットするにはrestart identityをつける

Posted at

PostgreSQLでtruncate tableでテーブルを空っぽにする際、同時にIDなどのシーケンスをリセットして0に戻すには、クエリにrestart identityを付け加えます。

truncate table product restart identity;

実行例

-- テーブルを作る
create table product (id serial, name varchar);

-- シーケンスを2つ消費する
insert into product (name) values ('item1'), ('item2');

-- テーブルの内容
select * from product;
--  id | name
-- ----+-------
--   1 | item1
--   2 | item2
-- (2 rows)

-- テーブルを空っぽにしつつ、シーケンスをリセットする
truncate table product restart identity;

-- シーケンスを2つ消費する
insert into product (name) values ('item1'), ('item2');

-- テーブルを確認すると1から発番されなおされている
select * from product;
--  id | name
-- ----+-------
--   1 | item1
--   2 | item2
-- (2 rows)
6
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
6
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?