2
2

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: シーケンスの次の値を発番するにはnextvalを使う

Posted at

PostgreSQLでシーケンスIDの次の値を発番するクエリです。

select nextval('project_id_seq') as "projectId";

解説

シーケンス名を引数にnextval()関数を実行すると次のシーケンス値を取得できます。

取得されるシーケンス値の型はbigintです。PostgreSQLのクライアントサイドのプログラミング言語やライブラリによってはbigintをそのプログラミング言語のstring型にマッピングすることがあります。その場合は、cast(nextval('...') as int)のようにSQLで型変換を行うことで数値型にマッピングできるかもしれません。

as "projectId"の部分は必要ないですが、このエイリアスを指定しない場合、カラム名がnextvalになります。

実行例

-- テーブルを作る
create table project (id serial not null);

-- IDを発番する
select nextval('project_id_seq') as "projectId";

実行結果

 projectId
-----------
         1
(1 row)
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?