Re: Parent Id - Mailing list pgsql-general

From Bruno Wolff III
Subject Re: Parent Id
Date
Msg-id 20031009202016.GB15173@wolff.to
Whole thread Raw
In response to Re: Parent Id  (Gene Vital <genevital@karibe.com>)
Responses Re: Parent Id
List pgsql-general
On Thu, Oct 09, 2003 at 15:55:27 -0400,
  Gene Vital <genevital@karibe.com> wrote:
> have an example :)
>
> Bruno Wolff III wrote:
>
> >On Thu, Oct 09, 2003 at 14:26:21 -0400,
> >  Gene Vital <genevital@karibe.com> wrote:
> >
> >>when inserting new records into  parent / child tables, what is the best
> >>recommended way of retrieving the pkey value from the parent table when
> >>using auto incrementing fields ?
> >
> >
> >You want to use currval. currval will return the last value obtained
> >by nextval in the same session, so it is safe to use without any additional
> >locking.
> >

You would do something like:
insert into parent_table (pk, col1, col2) values (default, 'val1', 'val2');
insert into child_table (pk, parent, col1, col2)
  values (default, currval('parent_table_pk_seq'), 'val3', 'val4');

I don't remember when being able to use default in insert statements was
added. You may need to just leave the pk columns off the list. I added them
so that you could see what the normal sequence name looks like. I also
assume that the two pk columns are declared to be of type serial. If not,
then you have to do the sequence and default creation yourself.

pgsql-general by date:

Previous
From: Bruno Wolff III
Date:
Subject: Re: Domains (was Re: int1?)
Next
From: Ron Johnson
Date:
Subject: Re: Domains (was Re: int1?)