473,793 Members | 2,894 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
25 11110
On Wednesday 12 November 2003 12:31, Doug McNaught wrote:
Scott Chapman <sc********@mis chko.com> writes:
On Wednesday 12 November 2003 11:29, Doug McNaught wrote:
Scott Chapman <sc********@mis chko.com> writes:
> It would be nice if PostgreSQL could return the primary key it
> inserted with but that may not be a fool-proof solution either.
> Is there a nice way to handle this situation?

Write a database function that inserts the record and returns the
primary key value? That's probably the best way to insulate your
app from the database structure...


The function still has to know which sequence to pull from doesn't
it?


Yes. It's theoretically possible to derive that information if you
have enough system-tables-fu, but since the function knows which
table it's inserting into, it's not hard to put the proper sequence
name in as well.
I don't know much about triggers/functions in PG. Is it possible
to have a function that intercepts the information AFTER the
sequence value is added as the new primary key and then return it?
This would enable the use of a more generic function.


Sure, in the function you would basically do (I forget the exact
pl/pgsql syntax):

INSERT INTO foo VALUES (...);
SELECT currval('the_pk _sequence') INTO pk;
RETURN pk;

Doesn't remove the need to know or derive the proper sequence name.
There is no "what primary key did I just insert" built into PG. And
you will need a separate function for each table.

But this way the DB knowledge resides in the DB and you just have a
nice clean API for inserting data from the clients. The schema can
change and the API will (homefully) remain the same...


What's the process to suggest changes to PG along these lines? Say, a
proposal to make it configurable for a user to have a INSERT return the
primary key that it just inserted rather than what it returns now?

Scott

---------------------------(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 #21
Scott Chapman <sc********@mis chko.com> writes:
What's the process to suggest changes to PG along these lines? Say, a
proposal to make it configurable for a user to have a INSERT return the
primary key that it just inserted rather than what it returns now?


What if you have a multicolumn PK?

I'm not actually sure PG keeps track of "primary keyness" -- I think
it translates a PRIMARY KEY constraint into NOT NULL UNIQUE when the
table is created. So it might be really hard to implement your
feature, even if you can figure out what should happen for multicolumn
PKs.

-Doug

---------------------------(end of broadcast)---------------------------
TIP 5: Have you checked our extensive FAQ?

http://www.postgresql.org/docs/faqs/FAQ.html

Nov 12 '05 #22
On Wed, Nov 12, 2003 at 12:35:27PM -0800, Scott Chapman wrote:
What's the process to suggest changes to PG along these lines? Say, a
proposal to make it configurable for a user to have a INSERT return the
primary key that it just inserted rather than what it returns now?


Take a well-worked-out proposal to the folks on -hackers, and either
wait for someone else to do the work (unlikely), or do the work
yourself, and submit a patch.

A

--
----
Andrew Sullivan 204-4141 Yonge Street
Afilias Canada Toronto, Ontario Canada
<an****@liberty rms.info> M2P 2A8
+1 416 646 3304 x110
---------------------------(end of broadcast)---------------------------
TIP 6: Have you searched our list archives?

http://archives.postgresql.org

Nov 12 '05 #23
On Wed, 12 Nov 2003, Scott Chapman wrote:
On Wednesday 12 November 2003 12:31, Doug McNaught wrote:
Scott Chapman <sc********@mis chko.com> writes:
On Wednesday 12 November 2003 11:29, Doug McNaught wrote:
> Scott Chapman <sc********@mis chko.com> writes:
> > It would be nice if PostgreSQL could return the primary key it
> > inserted with but that may not be a fool-proof solution either.
> > Is there a nice way to handle this situation?
>
> Write a database function that inserts the record and returns the
> primary key value? That's probably the best way to insulate your
> app from the database structure...

The function still has to know which sequence to pull from doesn't
it?


Yes. It's theoretically possible to derive that information if you
have enough system-tables-fu, but since the function knows which
table it's inserting into, it's not hard to put the proper sequence
name in as well.
I don't know much about triggers/functions in PG. Is it possible
to have a function that intercepts the information AFTER the
sequence value is added as the new primary key and then return it?
This would enable the use of a more generic function.


Sure, in the function you would basically do (I forget the exact
pl/pgsql syntax):

INSERT INTO foo VALUES (...);
SELECT currval('the_pk _sequence') INTO pk;
RETURN pk;

Doesn't remove the need to know or derive the proper sequence name.
There is no "what primary key did I just insert" built into PG. And
you will need a separate function for each table.

But this way the DB knowledge resides in the DB and you just have a
nice clean API for inserting data from the clients. The schema can
change and the API will (homefully) remain the same...


What's the process to suggest changes to PG along these lines? Say, a
proposal to make it configurable for a user to have a INSERT return the
primary key that it just inserted rather than what it returns now?


I wouldn't suggest changing current bevaiour (i.e. the number of rows
inserted is probably a SQL SPEC thing) but to have each serial column in a
table be addressable so you'd just do:

select tablename.field name.currval;

and you'd get the currval back for the serial. note that if the serial
value was implemented by hand like:

create table test (id int primary key default
'myseq'::text|| nextval('seqnam e')::text);

that currval or the equivalent would actually give back the key inserted,
'myseqx' where x was the sequence number.

The folks are -hackers are always willing to listen to a good idea, but
they've got plenty on their plates, so this kind of thing needs to be at
the least thought out well enough so they won't have lots of
implementation problems with the plan.

It might also be possible to have the serial type create a plsql function
that has the name tablename_field name_currval() and returns the last
currval('seqnam e') with a simple wrapper. That solution would be fairly
easy to implement, and would be quite useful.
---------------------------(end of broadcast)---------------------------
TIP 8: explain analyze is your friend

Nov 12 '05 #24
Doug McNaught <do**@mcnaught. org> writes:
Scott Chapman <sc********@mis chko.com> writes:
What's the process to suggest changes to PG along these lines? Say, a
proposal to make it configurable for a user to have a INSERT return the
primary key that it just inserted rather than what it returns now?
What if you have a multicolumn PK?


Or a PK that's not an integer? Or no PK at all?

There's not likely to be any interest in hotwiring INSERT to return
a different command tag than it does now; that would break too much
existing code. There has been some talk of inventing an "INSERT
.... RETURNING ..." syntax extension that would return whatever
expressions you cared to compute from inserted rows --- but in the form
of a SELECT result, not by trying to squeeze it into a command tag.
I think the last discussion of this was a year or so back in pg-hackers.

regards, tom lane

---------------------------(end of broadcast)---------------------------
TIP 1: subscribe and unsubscribe commands go to ma*******@postg resql.org

Nov 12 '05 #25

"scott.marl owe" <sc***********@ ihs.com> writes:
select tablename.field name.currval;


That syntax would be problematic, it would mean to select all rows from
tablename and evaluate fieldname.currv al for each one. Actually it's worse, it
would be confused with schemas I think.

The postgres-ish way to do this would be to create a function like currval
that took a table and column and told you the currval of the sequence
associated with it.

Well you can already do something like that:

db=> create or replace function currval(text,te xt) returns bigint as 'select currval($1 || ''_'' || $2 || ''_seq'')' language sql strict;
CREATE FUNCTION

db=> create table test (a serial);
NOTICE: CREATE TABLE will create implicit sequence "test_a_seq " for "serial" column "test.a"
CREATE TABLE

db=> insert into test(a) values (default);
INSERT 14080230 1

db=> select currval('test', 'a');
currval
---------
1
(1 row)

The only problem arises if you use table names or column names that cause
postgres to truncate the resulting sequence name. This could be worked-around
by using the dependency information instead of depending on the naming scheme.

But as long as you do that the above works fine. And means you could always
change your naming scheme or method for looking up the associated sequence
later without changing all your sql.

--
greg
---------------------------(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 #26

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
12665
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
10216
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
15230
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
7325
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
3043
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
9671
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
9518
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10433
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
10212
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
10000
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
9035
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
6777
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
5560
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2919
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.