473,729 Members | 2,359 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

GET LAST ID INSERT

I have a little problem.

there is a way to get last id inserted into db or i have to make a new query?

I explain better my question:

in vbscript using sqlserver2000 i can use this code:

varBookmark=rs. Bookmark
rs.Update
rs.Bookmark=var Bookmark

in this way in I the new id just inserted!!!

how can i do this with postgres?
there is a way?

thanks
Nov 11 '05 #1
6 47390
On Tue, 2003-09-23 at 09:24, Maurizio Faini wrote:
there is a way to get last id inserted into db or i have to make a new
query?


Typically, you will have created the table with a SERIAL column, whose
default value is taken from a sequence:

junk=# CREATE TABLE xxx (
junk(# id SERIAL PRIMARY KEY,
junk(# yyy TEXT
junk(# );
NOTICE: CREATE TABLE will create implicit sequence "xxx_id_seq " for
SERIAL column "xxx.id"
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index
"xxx_pkey" for table "xxx"
CREATE TABLE

Insert a row:
junk=# INSERT INTO xxx VALUES (DEFAULT, 'ljhldwtuy');
INSERT 1341077 1

Now get the value just created by the sequence:
junk=# SELECT currval('xxx_id _seq');
currval
---------
1
(1 row)

junk=# SELECT * FROM xxx WHERE id = 1;
id | yyy
----+-----------
1 | ljhldwtuy
(1 row)
Another way to do it, is to use the value returned by the INSERT
statement. If the table has oids, the first number returned (1341077 in
the example above) is the oid of the row just inserted. However, this
only works when a single row is inserted in a table with oids.

junk=# SELECT * FROM xxx WHERE oid = 1341077;
id | yyy
----+-----------
1 | ljhldwtuy
(1 row)

--
Oliver Elphick Ol************@ lfix.co.uk
Isle of Wight, UK http://www.lfix.co.uk/oliver
GPG: 1024D/3E1D0C1C: CA12 09E0 E8D5 8870 5839 932A 614D 4C34 3E1D 0C1C
=============== =============== ==========
"And we know that all things work together for good to
them that love God, to them who are the called
according to his purpose."
Romans 8:28
---------------------------(end of broadcast)---------------------------
TIP 1: subscribe and unsubscribe commands go to ma*******@postg resql.org

Nov 11 '05 #2
I'm using PHP in my App, and PHP have last_oid function - using this
function I've wrote function in plpgsql to get last inserted id:

CREATE FUNCTION "public"."last_ id" (bigint, varchar, varchar) RETURNS
text AS'
DECLARE
var_result RECORD;
var_query VARCHAR;
var_id TEXT;
BEGIN
var_query := ''SELECT '' || $3 ||'' AS __id FROM '' || $2 || '' WHERE
oid = '' || $1 || '';'';
IF $1 > 0 THEN
FOR var_result IN EXECUTE var_query LOOP
var_id := var_result.__id ;
END LOOP;
IF var_id > 0 THEN
RETURN var_id;
ELSE
RETURN NULL;
END IF;
END IF;
END;
'LANGUAGE 'plpgsql' VOLATILE RETURNS NULL ON NULL INPUT SECURITY
INVOKER;

Where:
Var $1 is "oid number"
Var $2 is "table_name "
Var $3 is "id_field_n ame"

Of course we can change this function and get table name automaticaly...
But in my case there is was need for this... But you can try.

Best wishes,
ML

-----Original Message-----
From: pg************* ****@postgresql .org
[mailto:pg****** ***********@pos tgresql.org] On Behalf Of
Maurizio Faini
Sent: Tuesday, September 23, 2003 9:25 AM
To: pg***********@p ostgresql.org
Subject: [GENERAL] GET LAST ID INSERT
I have a little problem.

there is a way to get last id inserted into db or i have to
make a new query?

I explain better my question:

in vbscript using sqlserver2000 i can use this code:

varBookmark=rs. Bookmark
rs.Update
rs.Bookmark=var Bookmark

in this way in I the new id just inserted!!!

how can i do this with postgres?
there is a way?

thanks

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



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

Nov 11 '05 #3
ol**@lfix.co.uk (Oliver Elphick) wrote in message news:<10******* *************** @linda.lfix.co. uk>...
On Tue, 2003-09-23 at 09:24, Maurizio Faini wrote:
there is a way to get last id inserted into db or i have to make a new
query?


Typically, you will have created the table with a SERIAL column, whose
default value is taken from a sequence:

junk=# CREATE TABLE xxx (
junk(# id SERIAL PRIMARY KEY,
junk(# yyy TEXT
junk(# );
NOTICE: CREATE TABLE will create implicit sequence "xxx_id_seq " for
SERIAL column "xxx.id"
NOTICE: CREATE TABLE / PRIMARY KEY will create implicit index
"xxx_pkey" for table "xxx"
CREATE TABLE

Insert a row:
junk=# INSERT INTO xxx VALUES (DEFAULT, 'ljhldwtuy');
INSERT 1341077 1

Now get the value just created by the sequence:
junk=# SELECT currval('xxx_id _seq');
currval
---------
1
(1 row)

junk=# SELECT * FROM xxx WHERE id = 1;
id | yyy
----+-----------
1 | ljhldwtuy
(1 row)
Another way to do it, is to use the value returned by the INSERT
statement. If the table has oids, the first number returned (1341077 in
the example above) is the oid of the row just inserted. However, this
only works when a single row is inserted in a table with oids.

junk=# SELECT * FROM xxx WHERE oid = 1341077;
id | yyy
----+-----------
1 | ljhldwtuy
(1 row)

--
Oliver Elphick Ol************@ lfix.co.uk
Isle of Wight, UK http://www.lfix.co.uk/oliver
GPG: 1024D/3E1D0C1C: CA12 09E0 E8D5 8870 5839 932A 614D 4C34 3E1D 0C1C
=============== =============== ==========
"And we know that all things work together for good to
them that love God, to them who are the called
according to his purpose."
Romans 8:28
---------------------------(end of broadcast)---------------------------
TIP 1: subscribe and unsubscribe commands go to ma*******@postg resql.org


Thank you very much!
I tried to use CURRVAL, but it gives me this error:
IS NOT YET DEFINED IN THIS SECTION
this is what i do:
1) INSERT (id,....) VALUES (nextval('...id _seq'),.....etc ...
2) SELECT currval('...id_ seq');
and now there is error.
3) get rs
4) another insert query with rs current val

why this not work?
where i make a mistake?

thank you.
Nov 11 '05 #4
On Wed, Sep 24, 2003 at 09:04:49AM +0100, Marek Lewczuk wrote:
BEGIN
var_query := ''SELECT '' || $3 ||'' AS __id FROM '' || $2 || '' WHERE
oid = '' || $1 || '';'';


Note that tables can be created without oids, and oids are not
automatically indexed. So this function might not work in future,
and will possibly be very slow.

A

--
----
Andrew Sullivan 204-4141 Yonge Street
Liberty RMS Toronto, Ontario Canada
<an****@liberty rms.info> M2P 2A8
+1 416 646 3304 x110
---------------------------(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 11 '05 #5
On Wed, 2003-09-24 at 11:49, Maurizio Faini wrote:
I tried to use CURRVAL, but it gives me this error:
IS NOT YET DEFINED IN THIS SECTION
That indicates that in the current session you haven't yet used
nextval() on the id specified in the currval() call.
this is what i do:
1) INSERT (id,....) VALUES (nextval('...id _seq'),.....etc ...
2) SELECT currval('...id_ seq');
and now there is error.
3) get rs
4) another insert query with rs current val

why this not work?
where i make a mistake?


I can't see what is wrong here. Please post a transcript of the actual
session; your editing has wiped out whatever you did wrong.

--
Oliver Elphick Ol************@ lfix.co.uk
Isle of Wight, UK http://www.lfix.co.uk/oliver
GPG: 1024D/3E1D0C1C: CA12 09E0 E8D5 8870 5839 932A 614D 4C34 3E1D 0C1C
=============== =============== ==========
"And we know that all things work together for good to
them that love God, to them who are the called
according to his purpose."
Romans 8:28
---------------------------(end of broadcast)---------------------------
TIP 8: explain analyze is your friend

Nov 12 '05 #6
I've found my mistake: I was closing my connection between first and
second point....

Now works.....thank you very much!!!!!


ol**@lfix.co.uk (Oliver Elphick) wrote in message news:<10******* *************** *@linda.lfix.co .uk>...
On Wed, 2003-09-24 at 11:49, Maurizio Faini wrote:
I tried to use CURRVAL, but it gives me this error:
IS NOT YET DEFINED IN THIS SECTION


That indicates that in the current session you haven't yet used
nextval() on the id specified in the currval() call.
this is what i do:
1) INSERT (id,....) VALUES (nextval('...id _seq'),.....etc ...
2) SELECT currval('...id_ seq');
and now there is error.
3) get rs
4) another insert query with rs current val

why this not work?
where i make a mistake?


I can't see what is wrong here. Please post a transcript of the actual
session; your editing has wiped out whatever you did wrong.

--
Oliver Elphick Ol************@ lfix.co.uk
Isle of Wight, UK http://www.lfix.co.uk/oliver
GPG: 1024D/3E1D0C1C: CA12 09E0 E8D5 8870 5839 932A 614D 4C34 3E1D 0C1C
=============== =============== ==========
"And we know that all things work together for good to
them that love God, to them who are the called
according to his purpose."
Romans 8:28
---------------------------(end of broadcast)---------------------------
TIP 8: explain analyze is your friend

Nov 12 '05 #7

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

Similar topics

2
3578
by: jdonnell | last post by:
I'm not very familiar with sql server or adodb. I'm writing a python script that uses adodb as described at http://www.ecp.cc/pyado.html, but I can't figure out how to get the id of my last insert.
0
1735
by: Andy | last post by:
I'm looking for a APi which will return the last inserted id, of a row inserted into a sql database. Thanks Andy http://www.coolchip-computers.co.uk/theshed/
1
37564
by: George Hill | last post by:
Hi I am trying to import several master detail records from files to ms sql server. I have orders file and order_items file that has several rows for each order. If I insert programmatically these records how can find out which order ID was the last inserted, so that I can attach the subsesquent row items to a proper order.
2
3843
by: Eugene | last post by:
Hi, Problem: I need to get the value of auto-incremented field from just inserted record In Oracle this is INSERT .. RETURNING command. In SQL Server there are @@IDENTITY, IDENT_CURRENT, SCOPE_IDENTITY - @@IDENTITY returns the value from the very LAST insert on any table
1
15959
by: Steve Leferve | last post by:
Hey folks - I have some VBA code for creating a row and related sub-rows from a 'wizard' form. I'm using sql 'INSERT' statements to create the rows. My problem is that I need to get the autonumber id field from the parent table to properly insert the rows in the subtable. PHP has a function for MySQL called mysql_last_id(). Is there something similar in VBA?
0
1006
by: Andrew Walsh | last post by:
Hello, I'm wondering if postgres has a way to determine the last transaction time (and even better, what the transaction was). I've read through the mail list archives and the only thing I've seen is a suggestion to stat the database files. Is there another way to do it using something within postgres (e.g. one of the pg_* tables?) Thank you,
2
1393
by: mg | last post by:
Hello, I use a access database with asp and i insert one record. I want to know the Id of the record inserted. thanks for help.
2
3089
by: saifmsg | last post by:
Hello everyone, I am using a custom php class where i have wrapped all the mysql connection settings and query functions. Instead of calling direct mysql functions i creat an instance of this class and than use the custon functions for query, connection etc. At some places i also use direct php mysql functions to connect and query. My problem is that on my web site sometime i dont get last insert id of an insert query. Is it because...
0
1926
by: saidev | last post by:
Hi All, One of the table has few data until yesterday and today when i query that table there are no rows. Can please anyone explain how to identify which user has delete and when last insert/update/delete happen agaisnt the table? Is there any catalog table that we can query for those info? Thanks in advance Dave
12
2816
by: azegurb | last post by:
I have table in Javascript and it has addrow, deleterow, submit, and functions. when i click it automatically adds new row and it has select option to choose some of them for ex. in added two rows one of them is Motherboard Asus and other is Motherboard Gigabyte. I would like to have a drop down combo box. When i chose one item from drop down menu and in the next row of input that option let not exist in drop down menu. Here is my code....
0
8763
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
9427
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
9284
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
9148
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
8151
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...
1
6722
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6022
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
4796
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2683
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.