Skip to content

Instantly share code, notes, and snippets.

@utamori
Last active August 27, 2020 07:47
Show Gist options
  • Select an option

  • Save utamori/90f345f57ce1b1a054b434318e898381 to your computer and use it in GitHub Desktop.

Select an option

Save utamori/90f345f57ce1b1a054b434318e898381 to your computer and use it in GitHub Desktop.

serial と identityの違い

https://stackoverflow.com/questions/55300370/postgresql-serial-vs-identity

質問

回答

serialは、Postgresで古くから使われてきた自動生成された一意の値の「古い」実装です。しかし、これはSQL標準の記法ではありません。

よりSQL標準に準拠するために、Postgres 10では、generated as identityを使用する構文が導入されました。

基本的な実装はまだシーケンスに基づいていますが、定義はSQL標準に準拠するようになりました。この新しい構文で可能になったことの一つは、値が誤って上書きされるのを防ぐことです。

以下の表を考えてみましょう。

create table t1 (id serial primary key);
create table t2 (id integer primary key generated always as identity);

以下を実行するとします

insert into t1 (id) values (1);

基底にあるシーケンスとテーブル内の値はもはや同期していません。 別の

insert into t1 default_values;

シーケンスが最初の挿入で進められなかったためにエラーが発生し、再度値1を挿入しようとします。

しかし、2つ目のテーブルでは

insert into t2 (id) values (1);
    ERROR: cannot insert into column "id"
    Detail: Column "id" is an identity column defined as GENERATED ALWAYS.

そのため、シーケンスの使用法を誤って「忘れてしまう」ことがあります。これを強制的に行うには、システム値の上書きオプションを使用します。

insert into t2 (id) overriding system value values (1);

これでもテーブルの値と同期していないシーケンスが残りますが、少なくともあなたはそれを認識していたことになります。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment