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

Similar Messages

  • HELP! How te retrieve the last row in MYSQL database using Servlet!

    Hi ,
    I am new servlets. I am trying to retireve the last row id inserted using the servlet.
    Could someone show me a working sample code on how to retrieve the last record inserted?
    Thanks
    MY CODE
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.io.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    public class demo_gr extends HttpServlet {
    //***** Servlet access to data base
    public void doPost (HttpServletRequest req, HttpServletResponse resp)
         throws ServletException, IOException
         String url = "jdbc:mysql://sql2.njit.edu/ki3_proj";
              String param1 = req.getParameter("param1");
              PrintWriter out = resp.getWriter();
              resp.setContentType("text/html");
              String semail, sfname, slname, rfname, rlname, remail, message;
              int cardType;
              sfname = req.getParameter("sfname");
              slname = req.getParameter("slname");
              rfname = req.getParameter("rfname");
              rlname = req.getParameter("rlname");
              semail = req.getParameter("semail");
              remail = req.getParameter("remail");
              message = req.getParameter("message");
              //cardType = req.getParameter("cardType");
              cardType = Integer.parseInt(req.getParameter("cardType"));
              out.println(" param1 " + param1 + "\n");
         String query = "SELECT * FROM greeting_db "
    + "WHERE id =" + param1 + "";
              String query2 ="INSERT INTO greeting_db (sfname, slname ,semail , rfname , rlname , remail , message , cardType ,sentdate ,vieweddate) values('";
              query2 = query2 + sfname +"','"+ slname + "','"+ semail + "','"+ rfname + "','"+ rlname + "','"+ remail + "','"+ message + "','"+ cardType + "',NOW(),NOW())";
              //out.println(" query2 " + query2 + "\n");
              if (semail.equals("") || sfname.equals("") ||
              slname.equals("") || rfname.equals("") ||
              rlname.equals("") || remail.equals("") ||
              message.equals(""))
                        out.println("<h3> Please Click the back button and fill in <b>all</b> fields</h3>");
                        out.close();
                        return;
              String title = "Your Card Has Been Sent";
              out.println("<BODY>\n" +
    "<H1 ALIGN=CENTER>" + title + "</H1>\n" );
                   out.println("\n" +
    "\n" +
    " From  " + sfname + ", " + slname + "\n <br> To  "
                                            + rfname + ", " + rlname + "\n <br>Receiver Email  " + remail + "\n<br> Your Message "
                                            + message + "\n<br> <br> :");
                   if (cardType ==1)
                        out.println("<IMG SRC=/WEB-INF/images/bentley.jpg>");
                   else if(cardType ==2) {
                        out.println("<IMG SRC=/WEB-INF/images/Bugatti.jpg>");
                   else if(cardType ==3) {
                        out.println(" <IMG SRC=/WEB-INF/images/castle.jpg>");
    else if(cardType ==4) {
                        out.println(" <IMG SRC=/WEB-INF/images/motocross.jpg>");
    else if(cardType ==5) {
                        out.println(" <IMG SRC=/WEB-INF/images/Mustang.jpg>");
    else if(cardType ==6) {
                        out.println("<IMG SRC=/WEB-INF/images/Mustang.jpg>");
    out.println("</BODY></HTML>");
         try {
              Class.forName ("com.mysql.jdbc.Driver");
              Connection con = DriverManager.getConnection
              ( url, "*****", "******" );
    Statement stmt = con.createStatement ();
                   stmt.execute (query2);
                   //String query3 = "SELECT LAST_INSERT_ID()";
                   //ResultSet rs = stmt.executeQuery (query3);
                   //int questionID = rs.getInt(1);
                   System.out.println("Total rows:"+questionID);
    stmt.close();
    con.close();
    } // end try
    catch (SQLException ex) {
              //PrintWriter out = resp.getWriter();
         resp.setContentType("text/html");
              while (ex != null) { 
         out.println ("SQL Exception: " + ex.getMessage ());
         ex = ex.getNextException ();
    } // end while
    } // end catch SQLException
    catch (java.lang.Exception ex) {
         //PrintWriter out = resp.getWriter();
              resp.setContentType("text/html");     
              out.println ("Exception: " + ex.getMessage ());
    } // end doGet
    private void printResultSet ( HttpServletResponse resp, ResultSet rs )
    throws SQLException {
    try {
              PrintWriter out = resp.getWriter();
         out.println("<html>");
         out.println("<head><title>jbs jdbc/mysql servlet</title></head>");
         out.println("<body>");
         out.println("<center><font color=AA0000>");
         out.println("<table border='1'>");
         int numCols = rs.getMetaData().getColumnCount ();
    while ( rs.next() ) {
              out.println("<tr>");
         for (int i=1; i<=numCols; i++) {
    out.print("<td>" + rs.getString(i) + "</td>" );
    } // end for
    out.println("</tr>");
    } // end while
         out.println("</table>");
         out.println("</font></center>");
         out.println("</body>");
         out.println("</html>");
         out.close();
         } // end try
    catch ( IOException except) {
    } // end catch
    } // end returnHTML
    } // end jbsJDBCServlet

    I dont know what table names and fields you have but
    say you have a table called XYZ which has a primary
    key field called keyID.
    So in order to get the last row inserted, you could
    do something like
    Select *
    from XYZ
    where keyID = (Select MAX(keyID) from XYZ);
    Good Luckwhat gubloo said is correct ...But this is all in MS SQL Server I don't know the syntax and key words in MYSQL
    This works fine if the emp_id is incremental and of type integer
    Query:
    select      *
    from      employee e,  (select max(emp_id) as emp_id from employee) z
    where      e.emp_id = z.emp_id
    or
    select top 1 * from employee order by emp_id descUday

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

  • How to retrieve the Last sequence value of a sequence ?

    Can anybody help me out regarding how to retrieve the last executed number or value of a sequence ? As dba_sequence.last_number does not show the original picture of that last value ?

    Rajesh Lathwal wrote:
    Last Number Selected From Sequence :
    SELECT sequence_name, last_number
    FROM user_sequences;That's wrong, this is taking the CACHE in account :
    SQL> create sequence seq ;
    Sequence created.
    SQL> select seq.nextval from dual;
       NEXTVAL
             1
    SQL> SELECT sequence_name, last_number
      2  FROM user_sequences where sequence_name='SEQ';
    SEQUENCE_NAME                  LAST_NUMBER
    SEQ                                     21
    SQL> select seq.currval from dual;
       CURRVAL
             1
    SQL>Nicolas.

  • How to retrieve the last 5 accessed record ??

    How to retrieve the last 5 accessed record ??
    I am using a field for storing the accessed time.
    Pls help with regard to this.
    Thanks in Advance.
    JG

    Depending on your used databasee version, there are several options available, here are just a few examples:
    Sorted Inline-Views & rownum:
    SELECT *
      FROM (SELECT *
              FROM user_objects
             ORDER BY timestamp desc)
    WHERE ROWNUM <= 5;        
    ;Inline-View with analytic function:
    SELECT *
      FROM (SELECT uo.*, ROW_NUMBER() OVER (ORDER BY timestamp desc) rn
              FROM user_objects uo
    WHERE rn <= 5;        
    ;C.

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

  • How to get the Interface inserted rows fom ODI Reporsitory

    hi,
    I need select query that will select the Interface inserted rows
    (Count) from ODI repository tables. because I want to maintain these records into another Oracle tables?????

    import datetime
    import sys
    import optparse
    document = []
    def docprint(string):
    document.append('%s' % string)n
    def docprintnocr(string):
    document.append('%s' % string)
    p = optparse.OptionParser()
    p.add_option('-a','--server',dest='server',default='XXX',help='The server with the ODI_W catalog')
    p.add_option('-b','--beginningday',dest='beginningday',type=int,default=1,help='The day to begin retrieval')
    p.add_option('-e','--endingday',dest='endingday',type=int,default=0,help='The day to end retrieval')
    p.add_option('-n','--session',dest='session',default='',help='Session to retrieve')
    p.add_option('-s','--step',dest='step',action='store_true',help='Print the step data')
    p.add_option('-t','--task',dest='task',action='store_true',help='Print the task data')
    p.add_option('-x','--recipientlist',dest='recipientlist',default='XXX',help='report recipient(s)')
    p.add_option('-y','--mailserver',dest='mailserver',default='XXX',help='mail server')
    p.add_option('-z','--mailuser',dest='mailuser',default='XXX',help='mail user')
    p.add_option('-p','--printonly',dest='printonly',action='store_true',help='Print, no e-mail')
    options,args = p.parse_args()
    docprint( '%s %s' \
    '\n\tserver=%s' \
    '\n\tbeginningday=%s' \
    '\n\tendingday=%s' \
    '\n\tsession=%s' \
    '\n\tstep=%s' \
    '\n\ttask=%s' \
    '\n\tprintonly=%s'
    sys.argv[0]
    ,datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    ,options.server
    ,options.beginningday
    ,options.endingday
    ,options.session
    ,options.step
    ,options.task
    ,options.printonly
    if options.server.upper() in ('XXX','YYY'):
    catalog = 'ODI_W'
    elif options.server in ('WWW','ZZZ'):
    catalog = 'SNP_W'
    else:
    print 'Unknown server %s' % options.server
    sys.exit(1)
    TimeEnd = datetime.datetime.now() - datetime.timedelta(options.endingday)
    TimeBegin = datetime.datetime.now() - datetime.timedelta(options.beginningday)
    TimeFormat = '%Y-%m-%d %H:%M:%S'
    if options.task:
    options.step = True
    docprint( '\n%s between %s and %s' %(
    options.server
    ,TimeBegin.strftime(TimeFormat)
    ,TimeEnd.strftime(TimeFormat)
    OptionString = ''
    if options.session:
    OptionString = '\nPrinting session %s' % options.session
    else:
    OptionString = '\nPrinting all sessions'
    if options.step:
    OptionString = '%s %s' % (OptionString,'with step detail')
    if options.task:
    OptionString = '%s %s' % (OptionString, 'and task detail')
    docprint(OptionString)
    import pyodbc
    ConnectString = 'DRIVER={SQL SERVER};SERVER=%s;DATABASE=%s;Trusted_Connection=yes' % (options.server.upper(),catalog)
    try:
    Connection = pyodbc.connect(ConnectString,autocommit=False)
    Cursor = Connection.cursor()
    except Exception, e:
    raise RuntimeError, '%s %s connect failed\n%s' % (options.server,catalog,e)
    SelectSession = """
    select
    S.SESS_NO
    ,S.SESS_NAME
    ,S.SESS_BEG
    ,S.SESS_END
    ,coalesce(S.SESS_DUR,0)
    ,S.SESS_STATUS
    ,S.CONTEXT_CODE
    from SNP_SESSION as S
    where S.SESS_BEG between ? and ?
    and S.SESS_BEG = (
    select max(SESS_BEG)
    from SNP_SESSION
    where SESS_NAME = S.SESS_NAME)
    order by S.SESS_BEG ASC
    SelectSessionHistory = """
    select Top 3
    SESS_NO
    ,SESS_NAME
    ,SESS_BEG
    ,SESS_END
    ,coalesce(SESS_DUR,0)
    ,SESS_STATUS
    ,CONTEXT_CODE
    from SNP_SESSION
    where SESS_NAME = ?
    and SESS_NO <> ?
    order by SESS_BEG DESC
    SESS_NO = 0
    SESS_NAME = 1
    SESS_BEG = 2
    SESS_END = 3
    SESS_DUR = 4
    SESS_STATUS = 5
    CONTEXT_CODE = 6
    SelectStep = """
    select
    LOG.STEP_BEG
    ,LOG.STEP_END
    ,coalesce(LOG.STEP_DUR,0)
    ,LOG.STEP_STATUS
    ,coalesce(LOG.NB_ROW,0)
    ,coalesce(LOG.NB_INS,0)
    ,coalesce(LOG.NB_UPD,0)
    ,coalesce(LOG.NB_DEL,0)
    ,coalesce(LOG.NB_ERR,0)
    ,STEP.STEP_NAME
    ,STEP.NNO
    from SNP_STEP_LOG LOG
    inner join SNP_SESS_STEP STEP
    on STEP.SESS_NO = LOG.SESS_NO
    and STEP.NNO = LOG.NNO
    WHERE LOG.SESS_NO = ?
    ORDER BY STEP.NNO
    STEP_BEG = 0
    STEP_END = 1
    STEP_DUR = 2
    STEP_STATUS = 3
    NB_ROW = 4
    NB_INS = 5
    NB_UPD = 6
    NB_DEL = 7
    NB_ERR = 8
    STEP_NAME = 9
    STEP_NO = 10
    SelectTask = """
    select
    LOG.TASK_BEG
    ,LOG.TASK_END
    ,coalesce(LOG.TASK_DUR,0)
    ,LOG.TASK_STATUS
    ,coalesce(LOG.NB_ROW,0)
    ,coalesce(LOG.NB_INS,0)
    ,coalesce(LOG.NB_UPD,0)
    ,coalesce(LOG.NB_DEL,0)
    ,coalesce(LOG.NB_ERR,0)
    ,TASK.TASK_NAME3
    from SNP_SESS_TASK_LOG LOG
    inner join SNP_SESS_TASK TASK
    on TASK.SESS_NO = LOG.SESS_NO
    and TASK.NNO = LOG.NNO
    and TASK.SCEN_TASK_NO = LOG.SCEN_TASK_NO
    WHERE LOG.SESS_NO = ?
    AND LOG.NNO = ?
    ORDER BY LOG.SCEN_TASK_NO
    TASK_BEG = 0
    TASK_END = 1
    TASK_DUR = 2
    TASK_STATUS = 3
    TASK_ROW = 4
    TASK_INS = 5
    TASK_UPD = 6
    TASK_DEL = 7
    TASK_ERR = 8
    TASK_NAME = 9
    SessionStatuses = {'M':'Warning','E':'Err','D':'Done','R':'Run'}
    StepStatuses = {'M':'Warn','E':'Err','D':'Done','W':'Wait','R':'Run'}
    SessionRows =Cursor.execute(SelectSession,(TimeBegin,TimeEnd)).fetchall()
    for SessionRow in SessionRows:
    if options.session and options.session.upper() != SessionRow[SESS_NAME].upper():
    # Not requested
    continue
    if SessionRow[SESS_NAME] in ('SOCKETSERVER','PROCESSHUB'):
    # Skip these utilities
    continue
    if SessionRow[SESS_STATUS] == 'R':
    # Still running, nothing to print(
    docprint( '\n%s, status %s' % (
    SessionRow[SESS_NAME]
    ,SessionStatuses[SessionRow[SESS_STATUS]]
    continue
    if SessionRow[SESS_END]:
    SessionEnd = SessionRow[SESS_END].strftime(TimeFormat)
    else:
    SessionEnd = ' '
    SessionHistories = Cursor.execute(SelectSessionHistory,(SessionRow[SESS_NAME],SessionRow[SESS_NO])).fetchall()
    docprintnocr( '\n%-20s\n\t%s / %s %6i secs %s' % (
    SessionRow[SESS_NAME][:20]
    ,SessionRow[SESS_BEG].strftime(TimeFormat)
    ,SessionEnd
    ,SessionRow[SESS_DUR]
    ,SessionStatuses[SessionRow[SESS_STATUS]]
    for SessionHistory in SessionHistories:
    if SessionHistory[SESS_END]:
    SessionHistoryEnd = SessionHistory[SESS_END].strftime(TimeFormat)
    else:
    SessionHistoryEnd = ' '
    docprintnocr( '\t%s / %s %6i secs %s' % (
    SessionHistory[SESS_BEG].strftime(TimeFormat)
    ,SessionHistoryEnd
    ,SessionHistory[SESS_DUR]
    ,SessionStatuses[SessionHistory[SESS_STATUS]]
    if not options.step:
    # Step detail not requested
    continue
    docprint( '\n %-22s %5s %4s %8s %8s %8s %8s %8s' % (
    ,'Secs'
    ,'Stat'
    ,'Rows'
    ,'Inserts'
    ,'Updates'
    ,'Deletes'
    ,'Errors'
    for StepRow in Cursor.execute(SelectStep,SessionRow[SESS_NO]).fetchall():
    try:
    docprint( ' %-22s %5i %-4s %8i %8i %8i %8i %8i' % (
    StepRow[STEP_NAME][:22]
    ,StepRow[STEP_DUR]
    ,StepStatuses[StepRow[STEP_STATUS]]
    ,StepRow[NB_ROW]
    ,StepRow[NB_INS]
    ,StepRow[NB_UPD]
    ,StepRow[NB_DEL]
    ,StepRow[NB_ERR]))
    except Exception, e:
    docprint(e)
    continue
    if not options.task:
    # Task detail not requested
    continue
    try:
    for TaskRow in Cursor.execute(SelectTask,(SessionRow[SESS_NO],StepRow[STEP_NO])).fetchall():
    docprint( ' %-21s %5i %-4s %8i %8i %8i %8i %8i' % (
    TaskRow[TASK_NAME][:21]
    ,TaskRow[TASK_DUR]
    ,TaskRow[TASK_STATUS]
    ,TaskRow[TASK_ROW]
    ,TaskRow[TASK_INS]
    ,TaskRow[TASK_UPD]
    ,TaskRow[TASK_DEL]
    ,TaskRow[TASK_ERR]
    except Exception, e:
    docprint( e )
    docprint( '\nEnd of report')
    Connection.close()
    if options.printonly:
    for line in document:
    print line
    sys.exit(0)
    import smtplib
    Message = """From: %s
    To: %s
    MIME-Version: 1.0
    Content-type: text/html
    Subject: %s
    <font face="courier" size="4"><b>%s</b></font>
    options.mailuser
    ,options.recipientlist
    ,'Session Report'
    ,'<br>'.join(document).replace('\n','<br>').replace('\t',' ').replace(' ',' ')
    server = smtplib.SMTP(options.mailserver)
    server.sendmail(options.mailuser,options.recipientlist,Message)
    server.quit()

  • How to populate the last empty row in Excel without using Report Generation Kit

    I wrote  a Labview SUb Vi that uses Report Generation Toolkit that is not loaded on the test stand. I am looking to convert it from Report Generation Vi like New Report,  Append Table to Report, Dispose Report. The tunneling through all the report generation Vis seems extensive. Code is attached. Thanks, Greg
    Greg

    Thank you that was a big help...
    I used the Excel Forum to get a lot of great ideas.  My code is almost working.
    There is a 2-D String Array that represents the String data that I am exporting to the Excel File Sheet 1 - 5.
    I am attempting to determine the last populated row in sheet 1 then populate the next row of Sheet 1.  Since all 5 sheets are populated every time, I should not have to search every sheet for the last row.
    I am getting two row populated on sheet 1 with seeming the same data.
     I found an AXExcelWrite2D ArrayWorksheet.vi that I thought would work.  I think there is a Table  determination that is causing me problems.  The link is http://lavag.org/topic/13324-labview-and-excel-activex-or-ado/.  The Application Invoke Node has a convert formula with "FromReferenceStyle" with R1C1 Attached to it.   I am not sure what this function is doing.  When I try to bring the function help up, there is a missing file.
    I am including both the new active x vi and the report generation vi.   Report Generation VI works.
    I would appreciate any assistance I can get on this.
    Thanks
    Greg
    Greg
    Attachments:
    REPU Test Data Population using Active X Write Save.vi ‏92 KB
    REPU Test Data Population.vi ‏60 KB

  • Result Set - How to retrieve the number of rows in resultset

    harlo....everyone.
    i m new in this language and would like to ask that how can i store the result into an array or u all hav others ideal to do it......? Hopefully can get answer asap....thanksssss.
    Below is the source code that i did. Please comment it
    ResultSet rs = stmt.executeQuery("Select CCourse_Code from RegisteredCourse, Student where Student.NStud_ID ='123'and Student.CStud_Pwd='123' and Student.NStud_ID = RegisteredCourse.NStud_ID ");
    if(rs!=null){
    // can i get the the number of records in resultset, rs to define my array size
    String course[] = new String[2];
    while(rs.next()){
    for(int i =0; i<course.length; i++)
    course[i] = rs.getString("ccourse_code");
    return course;

    Or...
    ResultSet rs = stmt.executeQuery("Select count(CCourse_Code) from RegisteredCourse, Student where Student.NStud_ID ='123'and Student.CStud_Pwd='123' and Student.NStud_ID = RegisteredCourse.NStud_ID ");
    This should return a table with one row and one column. This will hold the number originally requested.
    However I would still go with the ArrayList suggestion given above.

  • How to get the last row in a resultset or query

    Hi All
    Say If I have a complex query which returns a resultset say 15 rows. Now I want to limit the output showing only the last row.
    How can we do this

    Keep in mind Oracle does not keep "row" order as such. Unlike a graphical type db like Access, Oracle will not always give you back the results in order.
    Even if you were to use a sequence, your query is never guaranteed to give back the results in the order you are expecting. You must then give an order by statement to all queries expecting the order.
    Your definition of last row too is vague - if it is in fact the greatest amount, use the inline view suggestion. If you simply want to see the last inserted row, consider adding a last_update_date column inserting the sysdate (by a trigger perhaps). This would then allow you to see the last inserted row.
    Enjoy!

  • 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

  • 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

  • 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 value of last identity has been updated in a database?

    how to retrieve the value of last identity has been updated in a database

    Hi,
    Oracle 10g, FGA - Fine grained auditing, supports DML statements (9i only select).
    Set up FGA using the DBMS_FGA.ADD_POLICY procudure:
    sql> BEGIN
    DBMS_FGA.ADD_POLICY (
    policy_name => 'AUD_EMPLOYEE_SAL',
    object_schema => 'HR',
    object_name => 'EMPLOYEE',
    audit_column => SALARY',
    audit_condition => '',
    statement_type => 'UPDATE');
    END;
    NEXT:
    sql> SELECT dbuid, lsqltesxt FROM sys.fga_logs$;
    The database inserts the audit record into the FGA_LOG$ table using an autonomous transaction; even if you roll back the update statement, the update action will still be logged in this table. The fga_log$ tracks the session, machine id, timestamp, schema, scn, etc:
    SQL> desc fga_log$
    Name Null? Type
    SESSIONID NOT NULL NUMBER
    TIMESTAMP# DATE
    DBUID VARCHAR2(30)
    OSUID VARCHAR2(255)
    OSHST VARCHAR2(128)
    CLIENTID VARCHAR2(64)
    EXTID VARCHAR2(4000)
    OBJ$SCHEMA VARCHAR2(30)
    OBJ$NAME VARCHAR2(128)
    POLICYNAME VARCHAR2(30)
    SCN NUMBER
    SQLTEXT VARCHAR2(4000)
    LSQLTEXT CLOB
    SQLBIND VARCHAR2(4000)
    COMMENT$TEXT VARCHAR2(4000)
    PLHOL LONG
    STMT_TYPE NUMBER
    NTIMESTAMP# TIMESTAMP(6)
    PROXY$SID NUMBER
    USER$GUID VARCHAR2(32)
    INSTANCE# NUMBER
    PROCESS# VARCHAR2(16)
    XID RAW(8)
    AUDITID VARCHAR2(64)
    STATEMENT NUMBER
    ENTRYID NUMBER
    DBID NUMBER
    LSQLBIND CLOB
    SQL> spool off

Maybe you are looking for