Re: Parent Id

From: Bruno Wolff III <bruno(at)wolff(dot)to>
To: Gene Vital <genevital(at)karibe(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Parent Id
Date: 2003-10-09 20:20:16
Message-ID: 20031009202016.GB15173@wolff.to
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Thu, Oct 09, 2003 at 15:55:27 -0400,
Gene Vital <genevital(at)karibe(dot)com> wrote:
> have an example :)
>
> Bruno Wolff III wrote:
>
> >On Thu, Oct 09, 2003 at 14:26:21 -0400,
> > Gene Vital <genevital(at)karibe(dot)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.

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Ron Johnson 2003-10-09 20:24:09 Re: Domains (was Re: int1?)
Previous Message Bruno Wolff III 2003-10-09 20:13:52 Re: Domains (was Re: int1?)