473,783 Members | 2,354 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

SQL-question: returning the id of an insert querry

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Hi,

Im building an user database with many tables keeping the data for the
Address, Phone numbers, etc which are referenced by a table where I keep
the single users. My question is, how do I get the "Id"-value of a newly
inserted address to store it in the referencing user table:

(a) INSERT INTO address VALUES (....);

(b) INSERT INTO users VALUES ( name, ... , address , ... );

where address should hold the value of the Id from the Adress table.
Do have to do an
SELECT id FROM address WHERE oid = oid_returned_by _insert(a)
or something like that after doing the insert(a) to get the correct id
value, or is there a better way to do this.

Im writing my app in Perl with DBD/DBI
Thanks in advance,

Andreas Fromm

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQE/rhcdPkvkZVZzNY0 RApmDAJ4k4MY/zKvH2862MuHSIjD tsmIs3QCfRzaR
0zDc1bIQAOMpLur vRZ2V8JY=
=kgaA
-----END PGP SIGNATURE-----
---------------------------(end of broadcast)---------------------------
TIP 9: the planner will ignore your desire to choose an index scan if your
joining column's datatypes do not match

Nov 12 '05 #1
25 11109
After you've done the insert on the address table, you can use
currval('addres s_id_seq') (or equivalent) to get the ID. Ofcourse you have
to have used nextval() for the original insert.

Hope this helps,

On Sun, Nov 09, 2003 at 11:29:49AM +0100, Andreas Fromm wrote:
Hi,

Im building an user database with many tables keeping the data for the
Address, Phone numbers, etc which are referenced by a table where I keep
the single users. My question is, how do I get the "Id"-value of a newly
inserted address to store it in the referencing user table:

(a) INSERT INTO address VALUES (....);

(b) INSERT INTO users VALUES ( name, ... , address , ... );

where address should hold the value of the Id from the Adress table.


Do have to do an
SELECT id FROM address WHERE oid = oid_returned_by _insert(a)
or something like that after doing the insert(a) to get the correct id
value, or is there a better way to do this.

Im writing my app in Perl with DBD/DBI


Thanks in advance,

Andreas Fromm



---------------------------(end of broadcast)---------------------------
TIP 9: the planner will ignore your desire to choose an index scan if your
joining column's datatypes do not match
--
Martijn van Oosterhout <kl*****@svana. org> http://svana.org/kleptog/ "All that is needed for the forces of evil to triumph is for enough good
men to do nothing." - Edmond Burke
"The penalty good people pay for not being interested in politics is to be
governed by people worse than themselves." - Plato


-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.6 (GNU/Linux)
Comment: For info see http://www.gnupg.org

iD8DBQE/riFbY5Twig3Ge+Y RArk/AKDU1nU6pzTtFVY jWXwsV0Dd2VtYag CgiBm4
SCBl2fXmByxYY8+ wHZ965mQ=
=rQMo
-----END PGP SIGNATURE-----

Nov 12 '05 #2
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Martijn van Oosterhout wrote:
After you've done the insert on the address table, you can use
currval('addres s_id_seq') (or equivalent) to get the ID. Ofcourse you have
to have used nextval() for the original insert.

Hope this helps,

...going to try it. Thanks

Andreas Fromm

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.1 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQE/rkMwPkvkZVZzNY0 RAnajAJ0ePCTi/UODhGAxOs5NuptZ AT0tUgCgpNAz
Oqh8rM934O3SRRz v4Mh9S4I=
=E71z
-----END PGP SIGNATURE-----
---------------------------(end of broadcast)---------------------------
TIP 2: you can get off all lists at once with the unregister command
(send "unregister YourEmailAddres sHere" to ma*******@postg resql.org)

Nov 12 '05 #3
On Sunday 09 November 2003 03:13, Martijn van Oosterhout wrote:
After you've done the insert on the address table, you can use
currval('addres s_id_seq') (or equivalent) to get the ID. Ofcourse you
have to have used nextval() for the original insert.


What if someone else inserts another address before I get the currval?
I'm out of luck then, right?

---------------------------(end of broadcast)---------------------------
TIP 6: Have you searched our list archives?

http://archives.postgresql.org

Nov 12 '05 #4
Scott Chapman <sc********@mis chko.com> writes:
On Sunday 09 November 2003 03:13, Martijn van Oosterhout wrote:
After you've done the insert on the address table, you can use
currval('addres s_id_seq') (or equivalent) to get the ID. Ofcourse you
have to have used nextval() for the original insert.


What if someone else inserts another address before I get the currval?
I'm out of luck then, right?


No, currval() handles that--see the docs.

-Doug

---------------------------(end of broadcast)---------------------------
TIP 8: explain analyze is your friend

Nov 12 '05 #5
On Sun, Nov 09, 2003 at 10:26:51AM -0800, Scott Chapman wrote:
On Sunday 09 November 2003 03:13, Martijn van Oosterhout wrote:
After you've done the insert on the address table, you can use
currval('addres s_id_seq') (or equivalent) to get the ID. Ofcourse you
have to have used nextval() for the original insert.


What if someone else inserts another address before I get the currval?
I'm out of luck then, right?


No, currval is concurrency-safe. That's exactly what sequences are for.

--
Alvaro Herrera (<alvherre[a]dcc.uchile.cl>)
"I call it GNU/Linux. Except the GNU/ is silent." (Ben Reiter)

---------------------------(end of broadcast)---------------------------
TIP 8: explain analyze is your friend

Nov 12 '05 #6
On Sunday 09 November 2003 10:52, Alvaro Herrera wrote:
On Sun, Nov 09, 2003 at 10:26:51AM -0800, Scott Chapman wrote:
On Sunday 09 November 2003 03:13, Martijn van Oosterhout wrote:
After you've done the insert on the address table, you can use
currval('addres s_id_seq') (or equivalent) to get the ID. Ofcourse
you have to have used nextval() for the original insert.


What if someone else inserts another address before I get the
currval? I'm out of luck then, right?


No, currval is concurrency-safe. That's exactly what sequences are
for.


I just want to clarify what I mean here to make sure I understand this
right. I have a table, A, that has a ID field which defaults to nextval
of a sequence, SA.

Chronological events here:

X inserts a new record into A.
Y inserts a new record into A.
X fetches currval of the SA. What value does X get in this case, the one
from X's insert or Y's?

Scott

---------------------------(end of broadcast)---------------------------
TIP 9: the planner will ignore your desire to choose an index scan if your
joining column's datatypes do not match

Nov 12 '05 #7
On Mon, Nov 10, 2003 at 08:09:29AM -0800, Scott Chapman wrote:
Chronological events here:

X inserts a new record into A.
Y inserts a new record into A.
X fetches currval of the SA. What value does X get in this case, the one
from X's insert or Y's?


X's.

--
Alvaro Herrera (<alvherre[a]dcc.uchile.cl>)
"¿Qué importan los años? Lo que realmente importa es comprobar que
a fin de cuentas la mejor edad de la vida es estar vivo" (Mafalda)

---------------------------(end of broadcast)---------------------------
TIP 7: don't forget to increase your free space map settings

Nov 12 '05 #8
Are X & Y two different connections?
If you execute 2 statements on the same connection and then get currval()
it will give the last generated id.

Ex.
On 1 connection:
INSERT INTO A (fld) VALUES (val); -- id generated = 1
INSERT INTO A (fld) VALUES (val2); -- id generated = 2
SELECT currval('SA');
2

On 2 connections:
conn1.execute(" INSERT INTO A (fld) VALUES (val)") -- id generated = 1
conn2.execute(" INSERT INTO A (fld) VALUES (val2)") -- id generated = 2
conn1.execute(" SELECT currval('SA')")
1
conn2.execute(" SELECT currval('SA')")
2
David Green
Sage Automation, Inc
-----Original Message-----
From: pg************* ****@postgresql .org
[mailto:pg****** ***********@pos tgresql.org]On Behalf Of Scott Chapman
Sent: Monday, November 10, 2003 10:09 AM
To: Alvaro Herrera
Cc: Martijn van Oosterhout; Andreas Fromm; pg***********@p ostgresql.org
Subject: Re: [GENERAL] SQL-question: returning the id of an insert
querry
On Sunday 09 November 2003 10:52, Alvaro Herrera wrote:
On Sun, Nov 09, 2003 at 10:26:51AM -0800, Scott Chapman wrote:
On Sunday 09 November 2003 03:13, Martijn van Oosterhout wrote:
After you've done the insert on the address table, you can use
currval('addres s_id_seq') (or equivalent) to get the ID. Ofcourse
you have to have used nextval() for the original insert.


What if someone else inserts another address before I get the
currval? I'm out of luck then, right?


No, currval is concurrency-safe. That's exactly what sequences are
for.


I just want to clarify what I mean here to make sure I understand this
right. I have a table, A, that has a ID field which defaults to nextval
of a sequence, SA.

Chronological events here:

X inserts a new record into A.
Y inserts a new record into A.
X fetches currval of the SA. What value does X get in this case, the one
from X's insert or Y's?

Scott

---------------------------(end of broadcast)---------------------------
TIP 9: the planner will ignore your desire to choose an index scan if your
joining column's datatypes do not match
---------------------------(end of broadcast)---------------------------
TIP 3: if posting/reading through Usenet, please send an appropriate
subscribe-nomail command to ma*******@postg resql.org so that your
message can get through to the mailing list cleanly

Nov 12 '05 #9
On Monday 10 November 2003 08:23, David Green wrote:
Are X & Y two different connections?
If you execute 2 statements on the same connection and then get
currval() it will give the last generated id.

Ex.
On 1 connection:
INSERT INTO A (fld) VALUES (val); -- id generated = 1
INSERT INTO A (fld) VALUES (val2); -- id generated = 2
SELECT currval('SA');
2


Thanks for the clarification. With web applications and connection
pooling, it would appear that it's quite easy to get incorrect values
back. This is what I thought.

I talked with the author or SQLObject about this recently and I thnk
he's implementing this correctly, by querying the cursor for the last
OID?:

def _queryInsertID( self, conn, table, idName, names, values):
c = conn.cursor()
q = self._insertSQL (table, names, values)
if self.debug:
print 'QueryIns: %s' % q
c.execute(q)
c.execute('SELE CT %s FROM %s WHERE oid = %s'
% (idName, table, c.lastoid()))
return c.fetchone()[0]

The other way to do it would be to manually fetch nextval and insert
into the table over-riding the default for the ID field (assuming it
defaulted to the nextval in the sequence). I don't know which way is
best (for performance, for instance).

It's be nice if INSERT could be made to return the OID or (better yet)
the primary key field value when it completes. That would solve this
problem in one action and completely remove the need for the second
query. I expect it would have to be user-togglable so it didn't break
with existing code?

Scott

---------------------------(end of broadcast)---------------------------
TIP 6: Have you searched our list archives?

http://archives.postgresql.org

Nov 12 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
3354
by: cooldv | last post by:
i am running a website on Windows 2000 server with ASP 3 webpages and Access 2000 database. (with a hosting company) traffic is slow at this time but expect to grow. lately i have been reading about sql database and sql server, specially this article: http://www.aspfaq.com/show.asp?id=2195 will someone help me understand: 1. with *SQL Server*, do i keep my current Access 2000 database and ASP pages?
2
12664
by: Peter | last post by:
I run most of my SQL scripts via kornshell on AIX. I use the "here-document" to run some of the smaller ones. Example: #!/bin/ksh # Analyze the table. sqlplus ${SCHEMA_NM}/${SCHEMA_PASSWD}@${DB_NM} <<-ANALYZE_TABLE SET TERMOUT ON
0
10212
by: Jan | last post by:
I store sql-commands in a database table. In the first step I get the sql command out of the database table with embedded sql. In the second step I try to execute the command, which i got from the database table, using dynamic sql. Executing 'EXEC SQL DESCRIBE SELECT LIST FOR S INTO select_dp;' the error code -2149 is returned That means "Specified partition does not exist". Does anybody know if it is a database problem or a problem of
2
15229
by: Ken Lindner | last post by:
I have a need to become familiar with SQL Server 2000 for work. Needless to say I am new to SQL Server any version, but not IT in general. My employer has provided me with the SQL Server 2000 Personal disk from the SQL Server 2000 Enterprise kit as this is reported here on the MSDN web site to be the version that is supported on Windows XP. In fact so many of you kind people confess to having succeeded in doing it. I have tried...
2
7324
by: Yves Touze | last post by:
Hi All, I'm trying to migrate from SQL Server 7.0 to SQL Server 2000. I've got some ASP page which call VB components that retrieve shaped recordsets from SQL Server using the MSDATASHAPE provider. Precisely, here is the code i have Dim Cmdobj As New ADODB.Command Cmdobj.ActiveConnection = oconn Cmdobj.CommandType = adCmdStoredProc
9
669
by: Grim Reaper | last post by:
My work let me put SQL Server 7.0 Enterprise Edition on my laptop. I have never setup a server from the beginning, so I am a little new at creating server groups. Alright, I am trying to create a server group. I right click on the "SQL Server Group" and make a name of "TEST" and put in the subgroup of "SQL Server Group". Next, I try to register the "TEST" server group. I right click on the "TEST" server group and New Server Group...
4
7304
by: coosa | last post by:
Hi, I was installing SQL Server on my machine and during installation my PC freezed. It happens frequently on my machine. So i tried after restarting to install it again and since then i always get the same error message: "An error occurred while creating one or more registry entries. Please see C:\WINDOWS\sqlstp.log for details. The problem could be caused by a low registry quota condition" I have tried to clean the registry and i...
1
6642
by: Peter | last post by:
I've purchased VS.NET 2005 Standard and have tried to install SQL Server 2005 Express, but get the following error in the error log. Please could someone help me.... Microsoft SQL Server 2005 Express Edition x86: Component Microsoft SQL Server 2005 Express Edition x86 returned an unexpected value. ***EndOfSession***? Microsoft SQL Server 2005 Express Edition x86: Component Microsoft SQL Server 2005 Express Edition x86 returned an...
6
2507
by: Fuzzydave | last post by:
I am back developing futher our Python/CGI based web application run by a Postgres DB and as per usual I am having some issues. It Involves a lot of Legacy code. All the actual SQL Querys are stored in the .py files and run in the .cgi files. I have the problem that I need to construct a row from two seprate SQL Querys, I have tried combining the two Querys but all that does is create a Query that returns nothing after a long period...
14
3042
by: Developer | last post by:
Hello All, i have recently installed VS2005 and was trying to install SQL sever 2000. I have Win XP' SP2. But when I tried installing, it only installed client tools and not the database. Can anyone please help me with this as I want to install SQL server and also wouold be grateful, if you can suggest me any workaround to dealwith this problem.(Like should I install any new OS etc). Any help would be appreciated.
0
9643
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10313
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10147
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9946
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8968
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6735
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5378
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4044
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3643
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.