Re: Equivalent for AUTOINCREMENT?

From: Joshua Tolley <eggyknap(at)gmail(dot)com>
To: Michelle Konzack <linux4michelle(at)tamay-dogan(dot)net>
Cc: Nikolas Everett <nik9000(at)gmail(dot)com>, pgSQL - General <pgsql-general(at)postgresql(dot)org>
Subject: Re: Equivalent for AUTOINCREMENT?
Date: 2008-11-05 11:19:25
Message-ID: 20081105111925.GA18367@polonium.part.net
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: 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

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Joshua Tolley 2008-11-05 11:30:02 Re: [Fwd: Re: GEQO randomness?]
Previous Message Craig Ringer 2008-11-05 11:13:40 Re: Equivalent for AUTOINCREMENT?