How to fetch last inserted row in MySQL

Hi,
I am trying to get the last inserted row in MySql..but not able to fetch it.
this is what i used
i have one column order_id which is auto_increment
SELECT * FROM tablename WHERE order_id=(SELECT MAX(order_id) FROM tablename)
any help is appreciated .
the usage of lastinsert() method is also not successful
chintan

Hello
Given you have a date column, you can use it to determine the latest row. However, there is still a chance that two rows were inserted at exactly the same time in which case you will need something in addition to your date column to decide which is the latest...
The first option uses a sub query and the second uses analytics, as does the 3rd - however with the 3rd, if 2 rows have exactly the same date and time, it will pick one at random unless you include another column in the order by to determine the latest...
select
FROM
    your_table
WHERE
    your_date_column = (SELECT MAX(your_date_column) from your_table)
SELECT
FROM
        select
            a.*,
            MAX(your_date_column) OVER() max_date_column
        FROM
            your_table a
WHERE
    your_date_column = max_date_column
SELECT
FROM
        select
            a.*,
            ROW_NUMBER OVER(ORDER BY your_date_column DESC) rn
        FROM
            your_table a
WHERE
    rn = 1HTH
David

Similar Messages

  • Last Inserted Row in a Table

    Hi,
    I want to select only the last inserted row in a table. Can anybody help me how can i get it.
    Eg
    select * from emp;
    empno ename sal
    12 abc 100
    13 xyz 200
    Now i have inserted a row as
    Insert into emp values (14,'Rohit',500);
    So i only want to select the last inserted row i.e.. empno 14 (in this case).
    Thanks
    Bye
    Rohit Taneja

    Thanks to all for replying.
    But the result is not which i desire.
    I have deleted the existing row in the same table as
    SQL> Delete from emp where empno = 13;
    1 row deleted.
    Then i inserted a new row as
    SQL> insert into emp values(10,'SRI',200);
    1 row created.
    Then i committed the work
    SQL> commit;
    Commit complete.
    But still am getting the last row as
    SQL> select * from emp
    where rowid=(select max(rowid)
    from emp);
    EMPNO ENAME SAL
    14 ROHIT 500
    as the solution.
    But here i am supposed to get the row with empno 10.
    I have tried both the queries and still geting the same result.
    Please look aat it again,
    Thanks in advance
    Bye
    Rohit Taneja
    Hi,
    I want to select only the last inserted row in a
    table. Can anybody help me how can i get it.
    Eg
    select * from emp;
    empno ename sal
    12 abc 100
    13 xyz 200
    Now i have inserted a row as
    Insert into emp values (14,'Rohit',500);
    So i only want to select the last inserted row i.e..
    empno 14 (in this case).
    Thanks
    Bye
    Rohit Taneja

  • Getting the last inserted row

    Hi
    I want to get the ID for the last inserted row in another view (not the ones I have in my page), to pass it to a web service. How can I get it?
    This returns the first ID in the table: ${bindings.myIterator.RequestId}
    This one doesn’t work either: ${bindings.myIterator.currentRow.RequestId}
    It shows the following exception
    1. JBO-29000: Unexpected exception caught: java.lang.RuntimeException, msg=javax.servlet.jsp.el.ELException: Unable to find a value for "RequestId" in object of class "model.Travel_ViewRowImpl" using operator "."
    2. javax.servlet.jsp.el.ELException: Unable to find a value for "RequestId" in object of class "model.Travel_ViewRowImpl" using operator "."
    What does ${bindings.myIterator.currentRow.dataProvider} returns?

    Hi,
    while this is close to the correct syntax it is not complete
    ${bindings.myIterator.currentRow.RequestId}
    this would attempt to call set/get RequestId on the Row class, which doesn't have this property. It has a property getAttribute() but this doesn't allow you to pass an argumentbecause of EL limitations.
    Work around: Create an attribute binding for the "RequestId" attribute and call it with
    #{bindings.RequestId.inputValue}
    ADF always ensures that the currentRow's RequestId is the one obtained from the Attribute binding
    Frank

  • How to Commit before Insert Row when Press Create Insert Button ?

    Hi all;
    I'm Using JDev 11.1.1.2.0
    How to Commit before Insert Row when Press Create Insert Button in ADF11g?
    <af:commandButton actionListener="#{bindings.CreateInsert.execute}"
    text="CreateInsert"
    disabled="#{!bindings.CreateInsert.enabled}"
    id="cb8" />
    best regards;

    You need to do a custom method eather in managed bean or in Application module to do that.
    in managed bean it would be something like:
    public void CommitAndInsert(ActionEvent actionEvent) {
    OperationBinding opCommit = ADFUtils.findOperation("Commit");
    opCommit.execute();
    OperationBinding opCreateInsert = ADFUtils.findOperation("CreateInsert");
    opCreateInsert.execute();
    In page bindings Commit and CreateInsert must exist
    then the button actionListener will be
    <af:commandButton actionListener="#{backing.CommitAndInsert}"

  • 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.

  • Rownum and last inserted row !!!!!!!!!!!!

    hi everybody,
    I am at present using oracle 8i Release 2. According to my knowledge and "Oracle 8 complete reference", when we use ROWNUM, the rownum is decided when the data is selected from the database. So when we use "order by" clause actually the rownum gets jumbled up.
    But to my surprise when i did something like this on my SQl prompt row num is acting very "innocent" :)
    <Code>
    1* select rownum, empno from emp
    SQL> /
    ROWNUM EMPNO
    1 7369
    2 7499
    3 7521
    4 7566
    5 7654
    6 7698
    7 7782
    8 7788
    9 7839
    10 7844
    11 7876
    12 7900
    13 7902
    14 7934
    15 1
    15 rows selected.
    SQL> select rownum, empno from emp order by empno;
    ROWNUM EMPNO
    1 1
    2 7369
    3 7499
    4 7521
    5 7566
    6 7654
    7 7698
    8 7782
    9 7788
    10 7839
    11 7844
    12 7876
    13 7900
    14 7902
    15 7934
    15 rows selected.
    </Code>
    As you can see rownum is ordered again .. m i missing something.
    B)
    Is it possible to get a row that was inserted last. Does oracle guarantee that data retrieval will be according to the time of inssertion !!
    Thanx in advance
    Chetan

    Rownum is decided afeter the complete execution of ur SQL statment (it includes ordey by, group by, where etc.).
    you can get the last inserted row using:
    select * from emp where rowid=
    (select max(rowid) from emp);
    Regards
    Riaz

  • How to retrieve the last inserted row

    This may be a question with a very known answer but I couldn't find any within this forum.
    What is the proper way to retrieve the just inserted record ?
    I'm accessing the DB from external Java and at this moment I use a timestamp column in order to retrieve the inserted row. So I generate an unique timestamp ('20020615184524356') which I inserted during the insert operation. I retrieve the just inserted row using "select * from fooTable where(timestamp='20020615184524356')".
    Is this the general idea or am I totally wrong ?

    hi Shaik Khaleel,
    Just wanted to clarify my doubts regarding rowid.
    Please refer the subject as "abt rowid" in previous posting and ur reply for that was
    "its an unique number throughout the database, its an hexadecimal number. it assigns the rowid of the deleted row in future , but not to the immediate insertation row."
    As u have mentioned the rowid of the deleted row can be assigned to a new row in future,
    wont the following query fail.
    select * from temp where rowid=(select max(rowid) from temp); -- in oracle. ~chandru

  • How to: Display Last n Rows in a table

    I am currently running Crystal Reports XI and have been tasked with developing a report that displays only the last 30 rows in a table in ascending order (the records are used for showing data trends over time in a line graph). I have created a Command to extract the records, and by using the TOP 30 statement I can get the first 30 rows in proper order; however, in order to get the last 30 rows I have to sort the records in descending order. This gives me the last 30 rows that I need, but the data is in descending order. Is there another way to get the last 30 rows in a table so that the records come out in ascending order?
    The Command I am using looks like this:
    SELECT TOP 30 ROWID FROM MYTABLE ORDER BY ROWID DESC
    (The ROWID field is alpha numeric)

    Hi,
    Create a Group based on Rowid in the order-Ascending. This Group should contain all the fields that you require to print along with Rowid.  Therafter insert Summary like sum,count etc for for any field within the group of the type numbervar(numeric). This would activate the Group Sort Expert in the Report Menu. Click on it and select Bottom N (with N as 30) within nature of Sort and suppy the fieldname as Rowid.
    Hope this solves.....
    Thanks,
    Amogh.

  • How to get last inserted id from database

    Hello,
    In PHP Language, mysql_insert_id() gives the last inserted ID without writing any Queries in the code. Is there similar mechanism to do in Jsp page. I need to insert data in one table and in the meantime, with the last inserted ID i need to insert another sort of data in another table.
    Can u plz help me out?

    You can use Statement#getGeneratedKeys().
    The DDL should look like at least (you can use INT UNSIGNED instead, your choice):ID BIGINT AUTO_INCREMENT PRIMARY KEYBasic example:int affectedRows = statement.executeUpdate("INSERT INTO table (column1, column2) VALUES ('value1', 'value2')");
    Long insertID = null;
    if (affectedRows == 1) {
        ResultSet generatedKeys = statement.getGeneratedKeys();
        if (generatedKeys.next()) {
            insertID = new Long(generatedKeys.getLong(1));
    }Using MySQL Connector/J 5.0.

  • How to get the inserted row primary key with out  using select statement

    how to return the primary key of inserted row ,with out using select statement
    Edited by: 849614 on Apr 4, 2011 6:13 AM

    yes thanks to all ,who helped me .its working fine
    getGeneratedKeys
    String hh = "INSERT INTO DIPOFFERTE (DIPOFFERTEID,AUDITUSERIDMODIFIED)VALUES(DIPOFFERTE_SEQ.nextval,?)";
              String generatedColumns[] = {"DIPOFFERTEID"};
              PreparedStatement preparedStatement = null;
              try {
                   //String gen[] = {"DIPOFFERTEID"};
                   PreparedStatement pstmt = conn.prepareStatement(hh, generatedColumns);
                   pstmt.setLong(1, 1);
                   pstmt.executeUpdate();
                   ResultSet rs = pstmt.getGeneratedKeys();
                   rs.next();
    //               The generated order id
                   long orderId = rs.getLong(1);

  • How to include new inserted row in cursor

    Hi ...
    Is there anyway to include new inserted row into opened cursor ?
    consider the following code:
    declare
    cursor tbl_cur is select * from table1;
    -- table1 has two fields: no and name --
    begin
    for tbl_rec in tbl_cur
    loop
    -- if I insert some records here into table1, is there anyway that those just inserted records be included in tbl_cur so that can be proceed in for loop ? or anyway to include new inserted rows into opened cursor ?
    end loop;
    end;
    anyone response is highly appreciated.
    Thank You,
    SK.
    null

    If you re-open the cursor in another loop, the rows that you inserted in the previous loop will be included, along with the original rows.
    DECLARE
    CURSOR tbl_cur
    IS
    SELECT *
    FROM table1;
    BEGIN
    FOR tbl_rec IN tbl_cur
    LOOP
    INSERT INTO table1 (no, name)
    VALUES (tbl_rec.no + 1, 'test');
    END LOOP;
    FOR tbl_rec IN tbl_cur
    LOOP
    -- the rows you inserted in the loop
    -- above will be included here
    -- with the original rows
    END LOOP;
    END;
    null

  • URGENT: How to see the inserted row results in the ResultSet after an insertRow()?

    I want to see the inserted row in my result set immediately after I do an insertRow(). I don't want to do another select as my table has 100,000 records. I am using TYPE_SCROLL_SENSITIVE and CONCUR_UPDATABLE resultset with 8.1.7 thin driver.
    May be the driver does not support this because dbmd.ownInsertsAreVisible(ResultSet.TYPE_SCROLL_SENSITIVE)) always returns false. I just want to know is there a workaround or any solution for this problem. I would really appreciate if somebody could help me. Thanks in advance.

    Okay, first execute the query reqd. Then make whatever filters, navigational changes etc that are reqd. Once you are satisfied with the view of the data that you see on the screen, then from the Bex toolbar, click the Save button (Second from left) and choose the option Save as View Global. Give it a decsription and technical name.
    Hope this helps...

  • How to fetch last changed date for Header in me22n?

    Hi Experts,
    I need to create a report for PO, where I have created one screen tab in Header level(customer data), therefore I need to fetch last changed date for header , I must mention that I do not want last changed date for item level, only for header last changed date is required.
    Kindly assist me on this.
    Thanx
    Shireen

    Read table CDHDR (object "EINKBELEG") and CDPOS (look for table name EKKO), keep the last CDHDR record with "EKKO" data actually changed.
    Regards,
    Raymond

  • How to find last inserted values

    hello
    i want to find the last inserted values in order of their insertion.
    but i don't have primary key and date type field in the table.
    thanks

    If you don't have a primary key or a date field, then you will either have to add one, or create a sequence or create a trigger that will record such information.
    The information in a table (by definition of SQL) is like it was in a bag - when you SELECT you reach into the bag and grab whatever is available. There is no order implied at all. Ever.

  • How to get last insert/update/delet row of a table?

    I hava a table A and table B which is a copy of A. I want to create a trigger to record the changes of A in B. So every time inserting/updating/deleting A I record the row inserted/updated/deleted in B, But I can't find a effiencial way to get the latest row changed.
    So is there any sys_var in oracle table like cur_rowid or something to record the latest inserted/updated/deleted in a table? I don't want to check a index or a table to get the max_seq_id again.

    user11228816 wrote:
    I hava a table A and table B which is a copy of A. I want to create a trigger to record the changes of A in B. So every time inserting/updating/deleting A I record the row inserted/updated/deleted in B, But I can't find a effiencial way to get the latest row changed.
    So is there any sys_var in oracle table like cur_rowid or something to record the latest inserted/updated/deleted in a table? I don't want to check a index or a table to get the max_seq_id again.Sounds like an ugly requirement, any reason you're not going for materialized views or advanced replication here?

Maybe you are looking for