Re: Equivalent for AUTOINCREMENT? - Mailing list pgsql-general

From Joshua Tolley
Subject Re: Equivalent for AUTOINCREMENT?
Date
Msg-id 20081105111925.GA18367@polonium.part.net
Whole thread Raw
In response to Re: Equivalent for AUTOINCREMENT?  (Michelle Konzack <linux4michelle@tamay-dogan.net>)
List pgsql-general
On Sat, Nov 01, 2008 at 02:24:37PM +0100, Michelle Konzack wrote:
> Du I need to create a SEQUENCE for each table or do I need only  ONE  of
> if and can use it independant on differnt tables?

If you just create a bunch of tables with SERIAL or BIGSERIAL columns,
it will create one sequence for each column. But you can make a set of
such columns use the same sequence if you want. SERIAL and BIGSERIAL are
really just "syntactic sugar" which create a sequence and set the
column's default value to the next value in the sequence, like this:

jtolley=# create table a (id serial);
NOTICE:  CREATE TABLE will create implicit sequence "a_id_seq" for
serial column "a.id"
CREATE TABLE
jtolley=# \d a
                          Table "public.a"
 Column |  Type   |                   Modifiers
 --------+---------+------------------------------------------------
 id     | integer | not null default nextval('a_id_seq'::regclass)

If I need a new table or column using the same sequence, I just do this:

jtolley=# create table b (q integer not null default
nextval('a_id_seq'));
CREATE TABLE
jtolley=# \d b
                         Table "public.b"
 Column |  Type   |                   Modifiers
 --------+---------+------------------------------------------------
 q      | integer | not null default nextval('a_id_seq'::regclass)

- Josh / eggyknap

Attachment

pgsql-general by date:

Previous
From: Craig Ringer
Date:
Subject: Re: Equivalent for AUTOINCREMENT?
Next
From: Joshua Tolley
Date:
Subject: Re: [Fwd: Re: GEQO randomness?]