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?

More than 3 years have passed since last update.

PostgreSQLでカウンターを作る

Last updated at Posted at 2021-07-15

Webで連番のカウンターが必要な用件があったので実装を検討しました。普段使っているPostgreSQLの上にテーブルを作り、カウンターを実装しました。1追加してUPDATEした値が返ってきます。

テーブル実装

Create

テーブルを作成します。

create table mycounter(
 count_key varchar(16) PRIMARY KEY,
 count int8
);

Count

以下のようなQueryで一致するcount_keyが無い場合は1をセット、存在する場合はカウントアップをして、resultを返します。

INSERT INTO mycounter (count_key, count) VALUES ('MYCOUNTERKEY', 1)
ON CONFLICT ON CONSTRAINT mycounter_pkey
DO UPDATE SET count = mycounter.count + 1 RETURNING *;

シーケンスを使う

シーケンスを使っても連番を取得する事ができます。こちらの方がIDなどに使えるので応用がきくかもしれません。

Create

CREATE SEQUENCE my_seq; -- 指定無しで1 

Count等

select nextval('my_seq');  --次の値
select currval('my_seq');  --現在の値 
select setval('my_seq', 1);  --1に設定 

むにゃむにゃ

count_keyを変更する事で複数のカウンターを実装したり、日付別や月別での連番を生成する事ができるので、何かと役に立つかと思います。

0
0
1

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?