Skip site navigation (1) Skip section navigation (2)

Re: currval, lastval, nextvar?

From: "A(dot) Kretschmer" <andreas(dot)kretschmer(at)schollglas(dot)com>
To: pgsql-novice(at)postgresql(dot)org
Subject: Re: currval, lastval, nextvar?
Date: 2009-04-23 15:59:52
Message-ID: 20090423155952.GA20043@a-kretschmer.de (view raw or flat)
Thread:
Lists: pgsql-novice
In response to Carol Walter :
> Hello,
> 
> I want write a query that will insert a record in a person table,  
> insert a record in a presentation table, and then insert a record into  
> a bridge table that contains the keys of both of the newly created  
> records from the other two tables.  According to the documentation,  
> takes the next number in the sequence and reports it.  Both currval  
> and lastval report the last value that was taken from the sequence,  
> but both will produce errors if a "nextval" was not called in the  
> current session.  Does writing a record that automatically updates a  
> sequence count as calling nextval?

Yes. You don't need call nextval.

You can do something like :

test=# create table t1(id serial primary key);
NOTICE:  CREATE TABLE will create implicit sequence "t1_id_seq" for serial column "t1.id"
NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index "t1_pkey"
for table "t1"
CREATE TABLE
test=*# create table t2(id serial primary key);
NOTICE:  CREATE TABLE will create implicit sequence "t2_id_seq" for serial column "t2.id"
NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index "t2_pkey"
for table "t2"
CREATE TABLE
test=*# create table brige (i1 int references t1, i2 int references t2);
CREATE TABLE
test=*# insert into t1 values(default);
INSERT 0 1
test=*# insert into t2 values(default);
INSERT 0 1
test=*# insert into brige values (currval('t1_id_seq'), currval('t2_id_seq'));
INSERT 0 1
test=*# select * from brige ;
 i1 | i2
----+----
  1 |  1
(1 Zeile)


-- 
Andreas Kretschmer
Kontakt:  Heynitz: 035242/47150,   D1: 0160/7141639 (mehr: -> Header)
GnuPG-ID:   0x3FFF606C, privat 0x7F4584DA   http://wwwkeys.de.pgp.net

In response to

Responses

pgsql-novice by date

Next:From: Tom LaneDate: 2009-04-23 16:07:08
Subject: Re: currval, lastval, nextvar?
Previous:From: johnfDate: 2009-04-23 15:37:57
Subject: Re: currval, lastval, nextvar?

Privacy Policy | About PostgreSQL
Copyright © 1996-2014 The PostgreSQL Global Development Group