自動採番される列を含むテーブルを作る
やり方自体は簡単で、自動採番させたい列のデータ型に serial を指定するだけ。下の例では、システム側と Postgre 側にユーザー centos を設定済みで、データベース sampledb を作成済みです。
自動採番にはシーケンスを使うようですが(←よくわかっていない)、自動的に “テーブル名_列名_seq” の名前のシーケンスが作成されているようです。
[root@centos data]# su - centos
[centos@centos ~]$ psql sampledb
Welcome to psql 8.3.7, the PostgreSQL interactive terminal.
Type: \copyright for distribution terms
\h for help with SQL commands
\? for help with psql commands
\g or terminate with semicolon to execute query
\q to quit
sampledb=> CREATE TABLE table1
sampledb-> (id serial, nam varchar(20), pre varchar(10), ag text);
NOTICE: CREATE TABLE will create implicit sequence "table1_id_seq" for serial column "table1.id"
CREATE TABLE
データ型(type)に serial を指定してテーブルを作りましたが、"serial" というデータ型があるわけではないようです。
sampledb=> \d table1
Table "public.table1"
Column | Type | Modifiers
--------+-----------------------+-----------------------------------------------------
id | integer | not null default nextval('table1_id_seq'::regclass)
nam | character varying(20) |
pre | character varying(10) |
ag | text |
自動採番される列以外の列にデータを追加して、動作を確認してみます。
sampledb=> INSERT INTO table1 (nam, pre, ag) VALUES ('ピッコロ', 'ナメック星', 30);
INSERT 0 1
sampledb=> INERT INTO table1 (nam, pre, ag) VALUES ('ベジータ', '惑星べじーた', 28);
INSERT 0 1
sampledb=> select * from table1;
id | nam | pre | ag
----+----------+--------------+----
1 | ピッコロ | ナメック星 | 30
2 | ベジータ | 惑星べじーた | 28
(2 rows)
id にはデータを追加していないのにもかかわらず、自動的に番号が振られました。

COMMENT