Fetching the last inserted record

How can I fetch the last record inserted into oracle table?

Hi Waleed / Bhavesh
In pure RDBMS terms there is no concept of a first / last record. Also the query that Bhavesh has give makes an assumption that emp_n have been sequentially or inserted in some form of continuous incremental format.
It is not adviseable to use ROWNUM and ORDER BY together since Oracle allocates ROWNUMs before it actually orders the data

Similar Messages

  • Retrive a record before the last inserted record

    Hi,
    I use simple select statement to retrive records where cola = 'Yes':
    select * from tbl1
    where cola = 'Yes';
    The result gives me about 10 records with different date.
    From the above result, I want to get the record right before the last inserted record according to the date field; which means I can not use MAX function (all I want just one record).
    If I write a function to return a date and passes it back to the SELECT statement, I'll get a date for each record, which I don't want.
    I know there's a way to do that in PL/SQL.
    Plese help me.
    pem

    select * from (
    select * from
    (select * from (select * from (table> order by <date> desc) where rownum < 3)
    order by <date>) where rownum =1

  • How to get the last inserted record from a table ?

    :-) Hiee E'body
    I work on Oracle 8i and need to get the last
    record inserted in a table.
    I have tried using rownum and rowid pseudo-columns
    but that doesn't work.
    Can you please help me out ?
    :-) Have a nice time
    Vivek Kapoor.
    IT, Atul Ltd.,
    India.

    I'm not sure about 8i features.
    I assume here that you don't have 'Date-Time' stamp columns on the table which is the easiest way to determine the last inserted row in the table.
    If not try the following :-
    select address, piece, SQL_TEXT
    from V$SQLTEXT
    where upper(sql_text) like '%INSERT INTO TABLE_NAME%'
    Substiute the TABLE_NAME with the name of the actual table.
    Have fun.
    Regards,
    Shailender
    :-) Hiee E'body
    I work on Oracle 8i and need to get the last
    record inserted in a table.
    I have tried using rownum and rowid pseudo-columns
    but that doesn't work.
    Can you please help me out ?
    :-) Have a nice time
    Vivek Kapoor.
    IT, Atul Ltd.,
    India.

  • CREATING A TRIGGER THAT PICKS UP THE LAST INSERTED RECORD

    Hello everybody
    my question. is it possible to embed a sql query whitin a trigger? the thing is that when I have to insert the value, this actually would have to be retrieved from another table. It is an AFTER INSERT, but it needs to know which name I inserted in table 1 in order to also insert it into table 2.
    More specifically. Imagine a table with usernames and passwords that I populate as I set them up
    Then I need a trigger that as it sees that I have entered that username it takes it and populates another table with that plus a generated sequence that could be the result of some string function
    CREATE OR REPLACE
    TRIGGER GENERATE_SEQUENCE
    AFTER INSERT ON USERS_TABLE
    FOR EACH ROW
    BEGIN
    insert into GENERATED_SEQUENCES_TABLE (lastinserted_name,surrogate_key)
    values(SELECT USERNAME FROM USERS_TABLE WHERE USERID....., SUBSTR (lastinsertedname¦¦ password), 1,12);
    END;
    so, this lastinserted name is what I am trying to retrieve. I mean if it is not madness to insert a sql query in the way I have done it, I could write in the query to select the highest ID from the PK and that would give me the last inserted name.
    thanks a lot
    Alvaro

    In an insert trigger you can reference all the inserting values with :new.column_name, hence there's no need to select from the USERS_TABLE table:
    CREATE OR REPLACE
    TRIGGER GENERATE_SEQUENCE
    AFTER INSERT ON USERS_TABLE
    FOR EACH ROW
    BEGIN
    insert into GENERATED_SEQUENCES_TABLE (lastinserted_name,surrogate_key)
    values(:new.USERNAME, ...);
    END;
    /Max
    [My Italian Oracle blog|http://oracleitalia.wordpress.com/2010/02/05/gestione-degli-errori-in-sql-con-log-errors/]

  • How can I get the last / newest record of a table?

    Hi,
    I am developing an ecard app that has a create greeting page, a preview page with edit and send buttons and an edit page.
    I got he insert working, and on the preview page I created a master record page (displays all records), and delete all unecessary designs. Doing it this way also gives me the 'edit' button, so people are able to edit their page.
    How do I get only the last record displayed though? At the moment it loops through all records and displays them in sets of 10. I found the variable that holds the totla count of records ('$totalRows_rs7417_content1'), but how do I (re-)write the script so it ONLY diplays the last record?
    I need to get the ID of this record as I am writing this into the PARAMs of the object and embed tags of my message .swf (this picks up the ID and based on that sucks the greetings text out of the database via another php script.
    Also, from this page, how can I send an email to the sender (ie creator of the message) as well as the recipient? Both email addresses are in the databse so should be part of the erecord returned.
    Thanks,
    Nik

    -----
    OK, So how do I recreate what I got in a non-ADDT list?
    well, when you´re just about to display one certain record, the term "list" is somewhat inappropriate anyway.
    What you´d simply need to do IMHO, is using DW´s native functions to create the basic "SELECT * FROM table_name ORDEr BY ID DESC" query, add "LIMIT 1" manually, and display the desired "dynamic text" placeholders in 1 table cell -- don´t think there were any need for all the fancy stuff
    (sorting, filtering etc) provided by ADDT´s list, as it´s just 1 record.
    It also occurred to me just now that finding the last record that has been added *may-* notbe enough if the site gets used a lot by our executives (I am thinking of a situation where 2 or three peolpe create greetings at the same time and press submit and then getting each others messges rather than their own).
    in this case you might want to additionally store the respective executive´s "kt_login_id" session variable -- because it´s this unique "identifier" which should be used to show the last inserted record of the person who actually inserted it, means adding a "WHERE submitter_id" equals the session variable kt_login_id - clause to the query.
    When creating a non-ADDT list that´s at some point based on detecting a user session, you´ll BTW need to insert at line 1
    I can't seemt o insert it on the page as it is looking for a insert, update or delete bahaviour on the page which of course I don't have
    please search these forums for several posts I made which explain my "use dummy table" approach that´s made for cases when you actually don´t have anything to insert/update/delete, but need "something" for ADDT´s send email behaviours.
    Cheers,
    Günter Schenk
    Adobe Community Expert, Dreamweaver

  • Retrive last inserted  record  from database table

    Hi,
    some body inserting a record into table 'A' through some procedure/java program.i want to retrive the last inserted record from database table.records are not stored in order.Can any body help me.

    In general, unless you are storing a timestamp as part of the row or you have some sort of auditing in place, Oracle has no idea what the "first" or "last" record in a table is. Nor does it track when a row was inserted.
    - If you have the archived logs from the point in time when the row was inserted, you could use LogMiner to find the timestamp
    - If the insert happened recently (i.e. within hours), you may be able to use flashback query to get the value
    - If you're on 10g or later and the table was built with ROWDEPENDENCIES and the insert happened in the last few days and you can deal with a granularity of a few seconds and you don't need 100% accuracy, you could get the ORA_ROWSCN of the row and convert that to a timestamp.
    If this is something you contemplate needing, you need to store the data in the row or set up some sort of auditing.
    Justin

  • Last inserted record

    HI,
    we have created a table with a field ID.
    we have inserted 1000 records in that table,.
    I want to retrieve only the last inserted record.
    How it's possible?
    is it possible with rowid?
    e.g:
    CREATE TABLE TEST(id number(2));
    insert into TEST values(1);
    insert into TEST values(2);
    insert into TEST values(3);
    insert into TEST values(4);
    insert into TEST values(5);
    In this case i want to retrieve only 5.
    How we can achieve this?

    There is no concept of order in a heap table. Blocks can be reused so the ROWID cannot ever be used to determine when a row was inserted. The only way to determine the last row that was inserted into a table is to use a timestamp and/or a sequence column. If you need to determine the last inserted row and you don't already have a timestamp or sequence column, you need to add one.
    HTH
    David

  • GET LAST INSERTED RECORD

    I am fairly new to flex. So please bear with me no this
    question.
    I would like to get MYSQL ID of the last record I inserted.
    MSQL has as function LAST_INSERT_ID() that is connection based and
    will return the last id of the last inserted record. My thought was
    in the function contained within the cfc to do 2 queries insert the
    record and return the last id directly after (see below). However,
    I don't know how I would read the results back into flex. I am
    unsure how to write the event handler. Thanks
    <cffunction name="insertUser" access="remote"
    returntype="query" >
    <cfargument name="SSN" required="false" type="string"
    hint="SSN"/>
    <cfargument name="FNAME" required="false" type="string"
    hint="FNAME"/>
    <cfargument name="LNAME" required="false" type="string"
    hint="LNAME"/>
    <cfargument name="CLIENTID" required="false"
    type="string" hint="NEW CLIENTID"/>
    <cfquery name="insUser" datasource="DBT">
    INSERT INTO CLIENT (SSN, FNAME, LNAME) VALUES (
    <cfqueryparam value="#ARGUMENTS.SSN#"
    cfsqltype="CF_SQL_VARCHAR" maxlength="12"/>,
    <cfqueryparam value="#ARGUMENTS.FNAME#"
    cfsqltype="CF_SQL_VARCHAR" maxlength="20"/>,
    <cfqueryparam value="#ARGUMENTS.LNAME#"
    cfsqltype="CF_SQL_VARCHAR" maxlength="30"/>)
    </cfquery>
    <cfquery name="qRead" datasource="DBT">
    SELECT last_insert_id() AS CLIENTID
    </cfquery>
    <cfreturn qRead >
    </cffunction>

    I assume you have LCDS installed with CF and you are using
    the remote object service,
    <mx:RemoteObject
    id="myService"
    destination="ColdFusion"
    source="full.path.to.cfc"
    showBusyCursor="true">
    <mx:method name="insertUser"
    result="insertUser_result(event)" />
    </mx:RemoteObject>
    <mx:Scrpit>
    private function insertUser_result(event:ResultEvent) {
    trace(event.result);
    event.result will be the id of the newly inserted record.
    BTW, I would highly recommend you looking into the data
    management servcie. the SQLAssembler can spare you of the CF code
    for simple CRUDs like this.

  • Getting the last insert id

    Hi there,
    I'm trying to get the id of the last inserted record. Normally would use $last_id = mysql_insert_id() after the insert statemant but I can't work out how to get this value when I use a ADDT insert transaction.
    Any help much appreciated.
    Cheers

    I´m locking this thread because the OP has additionally added a related question to an existing thread, and a solution to this problem has been provided there too: using  mysql_insert_id() with the ADDT

  • How to find last inserted record in the table.

    Version: Oracle 10g
    I have a table called "Manufacture" and 3 columns as mfno,itemname,quantity.
    How to find last inserted record in the table "Manufacture".
    As i come to know that Rowid is not result perfect results. Please provide your inputs.

    user13416294 wrote:
    Version: Oracle 10gThat is not a version. That is a product name. A version is 10.1.0.2 or 10.2.0.4, etc.
    I have a table called "Manufacture" and 3 columns as mfno,itemname,quantity.
    How to find last inserted record in the table "Manufacture".Not possible as your data model does not cater for it. That simple.
    If there is a need to determine some order or associate some time to an entity, then that should be part of the data model - and a relationship, or one or more attributes are needed to represent that information. Thus your data model in this case is unable to meet your requirements.
    If the requirements are valid, fix the data model. In other words - your question has nothing to do with Oracle and nothing to do with rowid, rowscn or other pseudo columns in Oracle. It is a pure data modeling issue. Nothing more.

  • How to get the last inserted Autoincrement value in Java for Pervasive DB

    Hi, I need to get the last inserted auto incremented value after the record is inserted IN JAVA For ex. consider we have 4 columns for the myTable in the PERVASIVE DATABASE V10 autoid - identity column (auto increment column) userID userName pageID insertSqlExpression = insert into myTable (userID , userName, pageID) values( ? ,? ,?); prepareInsert = connection.prepareStatement(insertSqlExpression); prepareInsert .excuteUpdate; After inserting the new record how can I get the autoid value (last inserted value) in the Java. Please help me.
    Thanks in advance. Arthik

    JavaArthikBabu wrote:
    I dont have privileges to write new stored procedures in database.I need to do in the Java side only. In many databases that irrelevant. The same way you would do it in a proc can be done with the correctly conceived statement (singular.)
    For ex &#150; if we insert and then the select record's identity value as a single transaction and would this guarantee that what is returned by the select would not include inserts that another might have made?Please do not take that path unless you are absolutely certain that your database does not support any other way to do it.

  • Simple Query Question - How do I return the Last 3 records of a Table?

    Question.
    For example, I have a table that has 50 records.
    How do I, specify in SQL to only return the last 3 records of the table.
    Select a.* from table a where ????

    I was just trying to show an example to a friend on
    how something like this would work and if it was even possible. But it won't work. Here's a simple example:
    SQL> create table emp
      2  (id)
      3  as
      4  select object_id
      5  from   all_objects
      6  order  by object_id;
    Table created.
    SQL> select *
      2  from  (select rownum rn
      3               ,b.*
      4         from   emp b)
      5  where  rn > ( select (max(rownum) - 3)
      6                from    emp)
      7  ;
            RN         ID
         40830      55891
         40831      55892
         40832      55893So far, so good. These are the "last 3" rows inserted. Now delete a bunch of rows and insert 3 new ones:
    SQL> delete emp where id < 40000;
    33423 rows deleted.
    SQL> commit;
    Commit complete.
    SQL> insert into emp values (60000);
    1 row created.
    SQL> insert into emp values (60001);
    1 row created.
    SQL> insert into emp values (60002);
    1 row created.
    SQL> commit;
    Commit complete.
    SQL> select *
      2  from  (select rownum rn
      3               ,b.*
      4         from   emp b)
      5  where  rn > ( select (max(rownum) - 3)
      6                from    emp)
      7  ;
            RN         ID
          7410      55891
          7411      55892
          7412      55893Here's the problem. Even though the "last 3 rows" are 60000 - 60002, I still get the same ones as the first query.

  • The last insert in this procedure not inserting, logic of flow is right?

    Here is the code:
    { PROCEDURE prAddDATU (p_EXPCLLI            IN VARCHAR2,
    p_EXPIP IN VARCHAR2,
    p_EXPName IN VARCHAR2,
    p_EXPAddress IN VARCHAR2,
    p_EXPCity IN VARCHAR2,
    p_EXPState IN VARCHAR2,
    p_COPhoneNumber IN VARCHAR2,
    p_WCCLLI IN VARCHAR2,
    p_DialIn IN VARCHAR2,
    p_DialOut IN VARCHAR2,
    p_EXPRR IN VARCHAR2,
    p_PowerFuse IN VARCHAR2,
    p_HDFFrame IN VARCHAR2,
    p_PGTCFrame IN VARCHAR2,
    p_NTTFrame IN VARCHAR2,
    p_ColanRR IN VARCHAR2,
    p_ColanJack IN VARCHAR2,
    p_PollInterval IN NUMBER,
    p_LeadNPA IN NUMBER,
    p_EXPComments IN VARCHAR2,
    p_OwnerID IN NUMBER,
    p_LRNNumbers IN VARCHAR2,
    p_MaintBegin IN VARCHAR2,
    p_MaintEnd IN VARCHAR2,
    p_EXPPort IN NUMBER,
    p_LRNChecked IN VARCHAR2,
    p_LRNFacilityCode IN VARCHAR2,
    p_IsPrimaryAddress IN VARCHAR2,
    p_RTUTypeId IN NUMBER,
    p_SiteName IN VARCHAR2,
    p_HostExpIds IN VARCHAR2)
    IS
    v_DATUID NUMBER;
    v_HostExpId NUMBER;
    v_HostExpIds VARCHAR2 (200);
    v_LRN VARCHAR2 (30);
    v_LRNS VARCHAR2 (400);
    v_LRNActive CHAR (1);
    v_LRNSActive VARCHAR2 (20);
    v_LRNFacilityCode CHAR (2);
    v_LRNSFacilityCode VARCHAR2 (300);
    v_pos1 NUMBER;
    v_pos2 NUMBER;
    v_pos3 NUMBER;
    v_pos4 NUMBER;
    BEGIN
    SELECT DATU_EXP_UNIT_INFO_SEQ.NextVal INTO v_DATUID FROM DUAL;
    INSERT INTO TT_DATU_EXP_UNIT_INFO VALUES (v_DATUID, p_OwnerID, p_EXPName, p_EXPAddress, p_EXPCity, p_EXPState, p_COPhoneNumber, p_WCCLLI, p_EXPCLLI, p_EXPIP, p_EXPPort, p_DialIn, p_DialOut, p_EXPRR, p_PowerFuse, p_HDFFrame, p_PGTCFrame, p_NTTFrame, p_ColanRR, p_ColanJack, p_PollInterval, p_LeadNPA, NULL, p_EXPComments, p_MaintBegin, p_MaintEnd, p_IsPrimaryAddress, p_RTUTypeId, p_SiteName, Sysdate);
    -- Add New DATU in the TT_DATU_EXP_STAGING and TT_DATU_EXP_UNIT_INFO tables
    INSERT INTO TT_DATU_EXP_STAGING VALUES (v_DATUID, p_EXPCLLI, SysDate);
    -- Add New DATU in the TT_DATU_EXP_ALARM_INFO table with ALARM_TYPE = 'G0 - Staging'
    INSERT INTO TT_DATU_EXP_ALARM_INFO VALUES (v_DATUID, SysDate, 'G0', SysDate);
    -- Add RTU to Hosts
    v_HostExpIds := p_HostExpIds;
    v_pos1 := INSTR(v_HostExpIds, ',', 1);
    WHILE v_pos1 > 0
    LOOP
    v_HostExpId := TRIM(SUBSTR(v_HostExpIds, 1, v_pos1 - 1));
    IF v_HostExpId IS NOT NULL
    THEN
    INSERT INTO TT_HOST_SATELLITE VALUES (v_HostExpId, v_DATUID);
    END IF;
    v_HostExpIds := SUBSTR(v_HostExpIds, v_pos1 + 1, LENGTH(v_HostExpIds));
    v_pos1 := INSTR(v_HostExpIds, ',', 1);
    END LOOP;
    -- if LRN maps are entered add records in DATU_LRN_MAP
    v_LRNS := p_LRNNumbers;
    v_LRNSActive := p_LRNChecked;
    v_LRNSFacilityCode := p_LRNFacilityCode;
    v_pos1 := INSTR(v_LRNS, ',', 1);
    v_pos2 := INSTR(v_LRNSActive, ',', 1);
    v_pos3 := INSTR(v_LRNSFacilityCode, ',', 1);
    WHILE v_pos1 > 0
    LOOP
    v_LRN := TRIM(SUBSTR(v_LRNS, 1, v_pos1 - 1));
    v_LRNActive := TRIM(SUBSTR(v_LRNSActive, 1, v_pos2 - 1));
    v_LRNFacilityCode := TRIM(SUBSTR(v_LRNSFacilityCode, 1, v_pos3 - 1));
    IF v_LRN IS NOT NULL
    THEN
    INSERT INTO TT_DATU_LRN_MAP VALUES (v_LRN, v_DATUID, v_LRNActive, v_LRNFacilityCode);
    END IF;
    v_LRNS := SUBSTR(v_LRNS, v_pos1 + 1, LENGTH(v_LRNS));
    v_LRNSActive := SUBSTR(v_LRNSActive, v_pos2 + 1, LENGTH(v_LRNSActive));
    v_LRNSFacilityCode := SUBSTR(v_LRNSFacilityCode, v_pos3 + 1, LENGTH(v_LRNSFacilityCode));
    v_pos1 := INSTR(v_LRNS, ',', 1);
    v_pos2 := INSTR(v_LRNSActive, ',', 1);
    v_pos3 := INSTR(v_LRNSFacilityCode, ',', 1);
    END LOOP;
    COMMIT;
    END prAddDATU;
    The problem here is the last insert into TT_datu_lrn_map table shows no insert at all.
    Any guru can help, please.
    Thanks,

    I used an error table like the other post a ton. If you take a few minutes to review Handling Exceptions in PL/SQL you will be happy you did.
    You can add other columns to the table and add debug comments like 'Insert 1" in 'Insert 2' etc.
    BEGIN
    INSERT
    EXCEPTION
    WHEN ZERO_DIVIDE THEN
    END;
    There are several standard errors you can trap for example: (So you can trap for more than one at a time)
    -- Only one of the WHEN blocks is executed.
    WHEN CASE_NOT_FOUND -- ORA-06592
    dbms_output.put_line('Missing the else clause ');
    WHEN CURSOR_ALREADY_OPEN -- ORA-06511
    dbms_output.put_line('Close cursor first before reopening. ');
    WHEN DUP_VAL_ON_INDEX -- ORA-00001
    dbms_output.put_line('Attempt to store a duplicate value or values in a database column.');
    WHEN INVALID_CURSOR -- ORA-01001
    dbms_output.put_line('You tried to reference a cursor that does not yet exist. ');
    WHEN INVALID_NUMBER -- ORA-01722
    dbms_output.put_line('An attempt is made to convert a character string into a number failed ');
    WHEN LOGIN_DENIED -- ORA-01017
    dbms_output.put_line('Username is not a recognised username or that the password is incorrect ');
    WHEN NO_DATA_FOUND -- ORA-01403
    dbms_output.put_line('All records have been returned from the SQL query. ');
    WHEN ROWTYPE_MISMATCH -- ORA-06504
    dbms_output.put_line('Number and/or types of columns in a query does not match declared return type of a result set ');
    WHEN SYS_INVALID_ROWID -- ORA-01410
    dbms_output.put_line('Query for table for which there is no such row ');
    WHEN TOO_MANY_ROWS -- ORA-01422
    dbms_output.put_line('SELECT INTO statement returns more than one row ');
    WHEN VALUE_ERROR -- ORA-06502
    dbms_output.put_line('Unable to convert value. ');
    WHEN ZERO_DIVIDE THEN -- handles 'division by zero' error
    dbms_output.put_line('Company must have had zero earnings.');
    pe_ratio := null;
    WHEN OTHERS THEN -- handles all other errors
    dbms_output.put_line('Some other kind of error occurred.');
    END; -- exception handlers and block end here
    I hope this helps you.
    MS

  • Find the latest updated or the latest inserted record  in a table

    Hi All,
    Thanks in advance
    Just a simple question
    How do we find the latest updated or the latest inserted record in a table ?
    Provide some queries in SQL?

    You can order by rowid desc to get lately inserted records, but I'm not sure about updated records.That is incorrect, Oracle might use old rowid's even in inserts and you cannot assure that the max(rowid) refers to the latest record.
    If the table is created with rowdependencies one can use ORA_ROWSCN pseudo column to check on date/time when the last dml has been performed over that table. But, that has some limitations too, Old snapshots will be erased hence one can check the last dml with a time frame of few days.
    Regards,
    Prazy

  • Getting the last inserted ID

    I found out about a mySQL function that will get the last inserted autoincrement ID and I want to use it in my page. The prepared statement i am using look like this.
    PreparedStatement insertQuestion1 = ConninsertQuestion1.prepareStatement("INSERT INTO Question.question (Topic_ID, Description, Image, Author, Created_Date, Max_Score, Question_Type)  VALUES ('" + questionData.topicID + "', '" + questionData.questionText + "', '" + questionData.questionImage + "', '" +insertQuestion1__username+ "', '" + currentDate + "', " + questionData.maxScore + ", '" + questionData.questionType + "') ");
              insertQuestion1.executeUpdate();there is a function in mysql which looks like this.
    int mysql_insert_id (resource [link_identifier])
    How can i implement this in my code so i will be able to use the integer value later on to insert more records in another table.
    Help would be much appreciated
    Thanks

    If you are using Java1.4 the approach would be to use :
    public boolean execute(String sql,
    int autoGeneratedKeys)
    throws SQLException
    where the autoGeneratedKeys flag is set to Statement.RETURN_GENERATED_KEYS
    After the insert you can call the method :
    public ResultSet getGeneratedKeys()
    throws SQLException
    Which will return a ResultSet containing the mySQL auto-generated keys.
    Check the documentation
    http://java.sun.com/j2se/1.4.2/docs/api/java/sql/Statement.html
    Note that PreparedStatement inherits these methods from Statement

Maybe you are looking for