Just do IT

思うは招く

PostgreSQLで連番IDを自動で付与するようCREATEし、INSERTするまで

やりたいこと

  • PostgreSQLでテーブルに自動で連番idをつけたい
    • つまり自動インクリメント
  • INSERTの指定方法を知りたい

問題

こんなSQLファイルを書いて実行しようとした。

drop table if exists memos;
create table memos (
  id integer,
  title text,
  body text,
  primary key (id)
);

insert into memos (title, body) values ('test_title1', 'コメント1');
insert into memos (title, body) values ('test_title2', 'コメント2');
insert into memos (title, body) values ('test_title3', 'コメント3');

しかしこれだと、次のエラーが返る。

DROP TABLE
CREATE TABLE
psql:memos.sql:8: ERROR:  null value in column "id" violates not-null constraint
DETAIL:  Failing row contains (null, test_title1, コメント1).
psql:memos.sql:9: ERROR:  null value in column "id" violates not-null constraint
DETAIL:  Failing row contains (null, test_title2, コメント2).
psql:memos.sql:10: ERROR:  null value in column "id" violates not-null constraint
DETAIL:  Failing row contains (null, test_title3, コメント3).
  • idカラムにはprimary keyを設定しているし、not nullはダメ
  • でもidは自動で付与したいから、INSERT時にどう書けばいいの?

んで、いろいろ調べて解決した。

方法

結論としては、こう書けばよかった。

drop table if exists memos;
create table memos (
  id serial,
  title text,
  body text,
  primary key (id)
);

insert into memos (title, body) values ('test_title1', 'コメント1');
insert into memos (title, body) values ('test_title2', 'コメント2');
insert into memos (title, body) values ('test_title3', 'コメント3');
# 結果
DROP TABLE
CREATE TABLE
INSERT 0 1
INSERT 0 1
INSERT 0 1
  • idの属性をserialにしておけば、勝手に連番idを付与してくれる
  • INSERT時には特に指定する必要はない

PostgreSQLにログインして確認してみる。

sudo su - ユーザー名
psql -d データベース名
select * from テーブル名;

すると、

 id |    title    |   body    
----+-------------+-----------
  1 | test_title1 | コメント1
  2 | test_title2 | コメント2
  3 | test_title3 | コメント3
(3 rows)

idが自動で付与され、かつ連番になっている。

参照