Re: Autoincremental value

From: "gnari" <gnari(at)simnet(dot)is>
To: <adburne(at)asocmedrosario(dot)com(dot)ar>, <pgsql-general(at)postgresql(dot)org>
Subject: Re: Autoincremental value
Date: 2004-08-13 23:21:26
Message-ID: 003c01c4818c$41aeb630$0100000a@wp2000
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

From: <adburne(at)asocmedrosario(dot)com(dot)ar>:
> Hi I'm a newbie in postgresql, I came from MSSQL, MySQL and now
> I'm testing postgres.
> In mysql there is a way to make a second autoincrement field, just:
>
> create table table1
> (field1 integer,
> field2 integer autoincrement,
> primary key (field1,field2))
>
> when insert rows:
>
> insert into table1 (field1) values (1);
> insert into table1 (field1) values (1);
> insert into table1 (field1) values (2);
>
> and then select * from table1, you get:
> field1| field2
> ------+-------
> 1 | 1
> 1 | 2
> 2 | 1
> ------+-------
>
> there is a way to do this with postgres???

it seems it is possible with triggers:

create table table1 (
field1 integer,
field2 integer,
primary key (field1,field2)
);

create or replace function table1_subcnt()
returns trigger as '
begin
select coalesce(max(field2),0)+1 from table1
where field1=NEW.field1
into NEW.field2;
return NEW;
end;
' language plpgsql;

create trigger table1_subcnt before insert on table1
for each row execute procedure table1_subcnt();

insert into table1 (field1) values (1);
insert into table1 (field1) values (1);
insert into table1 (field1) values (2);

gnari=# select * from table1;
field1 | field2
--------+-------
1 | 1
1 | 2
2 | 1
(3 rows)

gnari

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Tom Lane 2004-08-13 23:29:43 Re: Re: We have got a serious problem with pg_clog/WAL synchronization
Previous Message Simon@2ndquadrant.com 2004-08-13 23:16:55 Re: Re: We have got a serious problem with pg_clog/WAL synchronization