pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Richard Huxton <dev@archonet.com>
To: mixo <mixo@coza.net.za>
Cc: pgsql-sql@postgresql.org
Subject: Re: Last insert id
Date: Wed, 09 Jun 2004 08:22:37 +0100
Message-ID: <40C6BABD.6060204@archonet.com> (raw)
In-Reply-To: <40C6AD19.70302@coza.net.za>
References: <40C6AD19.70302@coza.net.za>

mixo wrote:
> I have three tables which are related a serial field, table1_id, in on 
> of the tables. Updating the tables is done through a transaction. My 
> problem is, once I have insert  a row in the first tables with 
> table1_id, I need for the other two tables. How can I get this? Is it 
> safe to use "select max(table1_id) from table1" after the insert?

A SERIAL column is just an ordinary integer with a default of 
nextval(<sequence-name>).

All you need to do is:
INSERT INTO t1 (...) VALUES (...)
INSERT INTO t2 (...) VALUES (currval(<sequence-name-from-table1>)...)

Sequences are guaranteed to give values relevant to your current connection.

-- 
   Richard Huxton
   Archonet Ltd



view thread (6+ messages)  latest in thread

Message-ID: <40C6BABD.6060204@archonet.com>
Permalink:  ../40C6BABD.6060204@archonet.com/
Also on:    postgresql.org/message-id/40C6BABD.6060204@archonet.com

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: dev@archonet.com, mixo@coza.net.za
  Subject: Re: Last insert id
  In-Reply-To: <40C6BABD.6060204@archonet.com>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox