How to get the last row

I have 10 rows in my table and I have to retrive last row using rownum.
For this I use
SELECT * from <table_name>
where rownum<=10
minus
SELECT * from <table_name>
where rownum<=9
The result is no rows selected
In the same case if I use
SELECT rownum from <table_name>
Where rownum <= 10
minus
SELECT rownum from <table_name>
where rownum <=9
The result is 10
Why this happend.
If the result is 10, then why the row whose rowid is 10 is not retrived

All
Please bear in mind that ROWNUM is an attribute of the query NOT the table. The last row returned by an unORDERed SELECT statement may be the most recently inserted row but is not guaranteed to be so.
The only way of assuring yourself of returning the most recent row is either to timestamp all your tables with a date_created column or to use a primary key with an ascending value.
rgds, APC

Similar Messages

  • How to get the last row of a database table.

    HI ,
    I want to get record exactly from the last row of a database table.
    How is that possible?

    Hi,
    To fetch last record from an internal table, just do find the number of records in it and read using index.
    DESCRIBE TABLE ITAB LINES L_LINES.
    READ TABLE ITAB INDEX L_LINES.
    You can also use LOOP .. ENDLOOP but the above method is better (performance wise).
    using LOOP .. ENDLOOP.
    LOOP AT ITAB.
    **do nothing
    ENDLOOP.
    **process ITAB (Header record of ITAB).
    **after ENLOOP, ITAB will have the last record of the internal table.
    [here ITAB is internal table as well as header record.]
    But what is the requirement?
    If you are looking for the current record of an employee then you can use ENDDA = HIGH_DATE.
    My advice is to review your requirement again and try to fetch only that record which you need.
    Mubeen

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

  • 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

  • How to get the last day of the week?

    Hii
    i can get the calender week number for any given date using
    SELECT to_char(to_date('04/04/2011','MM/DD/YYYY'),'WW') FROM dual
    can any body tell me, how to get the last day of that week ?
    and the answer should be 04/08/2011(8th april )
    thanks
    San
    Edited by: sandeep9 on Apr 4, 2011 3:50 AM

    Hi, San,
    Here's one way:
    WITH     sample_data     AS
         SELECT  DATE '2011-04-04'     AS dt
         FROM     dual
    SELECT  dt
    ,     TO_CHAR (dt, 'WW')     AS week_num
    ,     NEXT_DAY ( dt - 1
               , TO_CHAR ( TRUNC (dt, 'YEAR') - 1
                      , 'Day'
               )          AS end_o_week
    FROM     sample_data;Another way is to use date arrithmetic:
    WITH     sample_data     AS
         SELECT  DATE '2011-04-09'     AS dt
         FROM     dual
    SELECT  dt
    ,     TO_CHAR (dt, 'WW')     AS week_num
    ,     TRUNC (dt, 'YEAR')
          + (7 * CEIL ( (dt - (TRUNC (dt, 'YEAR') - 1))
                / 7
          - 1               AS using_date_arithmetic
    FROM     sample_data;

  • How to get the last day of a month?

    HI,
    I want to know how to get the last day of a month.
    In my JClient form, I tried to get it by using oracle.sql.Date method, that is:
    lastday=oracle.sql.Date anydate.lastDayOfMonth();
    But it does not work. The result is lastday=anydate.
    Why?
    Stephen

    You can use the Calender class...
    Calendar c = Calendar.getInstance();
    and then something like...
    c.add(c.MONTH, 1);
    int dayOfMonth = c.get(Calender.MONTH);
    c.add(c.DAY_OF_MONTH, - (dayOfMonth-1) );
    other usefull functions are:
    System.out.println(" YEAR : " + c.get(Calendar.YEAR));
    System.out.println(" MONTH : " + c.get(Calendar.MONTH));
    System.out.println(" DAY_OF_MONTH : " + c.get(Calendar.DAY_OF_MONTH));
    System.out.println(" DAY_OF_WEEK : " + c.get(Calendar.DAY_OF_WEEK));
    System.out.println(" DAY_OF_YEAR : " + c.get(Calendar.DAY_OF_YEAR));
    System.out.println(" WEEK_OF_YEAR : " + c.get(Calendar.WEEK_OF_YEAR));
    System.out.println(" WEEK_OF_MONTH : " + c.get(Calendar.WEEK_OF_MONTH));
    System.out.println(" DAY_OF_WEEK_IN_MONTH : " + c.get(Calendar.DAY_OF_WEEK_IN_MONTH));
    System.out.println(" HOUR : " + c.get(Calendar.HOUR));
    System.out.println(" AM_PM : " + c.get(Calendar.AM_PM));
    System.out.println(" HOUR_OF_DAY (24-hour): " + c.get(Calendar.HOUR_OF_DAY));
    System.out.println(" MINUTE : " + c.get(Calendar.MINUTE));
    System.out.println(" SECOND : " + c.get(Calendar.SECOND));
    System.out.println();*/

  • How to get the last day according to fiscal period input in selection scree

    Hello expert
    how to get the last day of fiscal period input.
    the fiscal period inculdes 1-16
    when fiscal period is greater than 12, only calculate the last day of 12nd month
    your solution will be apprecaited, FM existing?
    thank you
    Kevin

    Hi,
    when you give a particular date in any month
    the following fm will give you the last date of that month
    here you can give
    R_FDATE-HIGH  as 01 and month as the period you wnat and year for current year
    concatenates '01'  month year  into r_fdate-high separated by '.'.
    then it will give g_ltdt for that month and year which wil be the last date of that month
        CALL FUNCTION 'RP_LAST_DAY_OF_MONTHS'
          EXPORTING
            DAY_IN            = R_FDATE-HIGH
          IMPORTING
            LAST_DAY_OF_MONTH = G_LTDT
          EXCEPTIONS
            DAY_IN_NO_DATE    = 1
            OTHERS            = 2.
        IF SY-SUBRC <> 0.
          MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
                  WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
        ENDIF.
    thanks & regards,
    Venkatesh

  • How to get the last error for while loop?

    How to get the last error for while loop? I just want transfer the last error for while loop, but the program use the shift register shift all error every cycle.

    What do you mean by "get" and "transfer"?
    If the shift register is not what you want, use a plan tunnel instead.
    Typically, programmers are interested in the first, not last, error.
    Can you show us your code so we have a better idea what you are trying to?
    LabVIEW Champion . Do more with less code and in less time .

  • How to get the last version of flash in MSI format automatically?

    How to get the last version of flash in MSI format automatically?
    Roberto Neigenfind
    Bravo Tecnologia
    www.bravotecnologia.com.br

    Hi Barbara,
    Flash Professional CS5.5 is a 32-bit application which can be installed on computers with either 32-bit or 64-bit operating systems.
    You can purchase this by Adobe's backward Licensing policy :
    " Adobe allows program members to order a current-version license but use a prior version. These members can contact Adobe Customer Service to request a serial number for the earlier version if they do not already have one. Prior-version software is available via ESD and can be purchased through standard resellers. The program member must follow all guidelines of the current-version EULA. "
    Please check the doc : http://www.adobe.com/volume-licensing/policies.html

  • How to get the "last changed by" for a set of function modules?

    How to get the "last changed by" for a set of function modules?
    is there any table to get it??

    See [this|Re: Date of creation of function module] I posted earlier.
    >TFDIR will give you the name of the function group program and the include number.
    >E.g. SAPLZFUNCGROUP Include 01.
    >From this you can construct the include name: LZFUNCGROUPU01.
    >You can look this up in TRDIR to find the creation date (CDAT) of the function module.
    In your case, you need unam and udat.
    matt

  • How to get the last page  SAP Script form

    How to get the last page  SAP Script form.
    I want to print a specific information in the last page of SAP form (Script). Please tell me how to get the last page number.
    Regards

    Hi
    You have to check the system variable &NEXTPAGE&, if it's 0 it means you're in the last page.
    From SAP Help:
    This symbol is used to print the number of the following page. The output format is the same as with &PAGE& .
    Note that on the last page of the output, in each window that is not of type MAIN, &NEXTPAGE& has the value 0.
    /: IF &NEXTPAGE& = '0'
       Last page
    /: ENDIF
    Max

  • Cant get the last row in jtable

    Hello all.
    I am trying to get the last row from the table but get "" from it.
    my table has 6 rows and i can get all rows right but the last line I have a problem.
            //creating the table
        for (i=0;i<this.rows;i++)
         model.insertRow(i,new Object[]{"input Y1:",""});
                for ( i=i;i<this.Amount+this.rows;i++)
         model.insertRow(i,new Object[]{"input Amount:",""});
    //end of creatingthis code creats the table that i need and its works right.
    for(i=0;i<rows;i++){
                  fObj.fullData[i] = Double.valueOf(GetData(table, 1, i).toString()).doubleValue();
            int j=0;
            String s=GetData(table, 1, 4).toString();
            //the problem line
            String s1=GetData(table, 1, 5).toString();
        public Object GetData(JTable table, int col_index, int row_index){
        return table.getModel().getValueAt(row_index, col_index);
      }this line i get ""
    String s1=GetData(table, 1, 5).toString();
    Edited by: vitaly87 on 00:41 08/04/2011

    vitaly87 wrote:
    Hello all.
    I am trying to get the last row from the table but get "" from it.
    my table has 6 rows and i can get all rows right but the last line I have a problem.
    this line i get ""
    String s1=GetData(table, 1, 5).toString();Looks right to me, given that your insert ismodel.insertRow(i,new Object[]{"input Amount:",""});(Hint: indexes start at *0* ).
    If it hadn't found the row, I expect you would have got an Exception
    Winston

  • How to get the last transaction in a row in SQL Developer?

    What syntax would I use to get the last transaction of a row in SQL developer?
    The way I have my query set-up currently it is not returning the correct data, here is my current syntax:
    select ssn, max(tran_id), chng_type,tran_id
    from pda_tran
    where ssn = 'xxx-xxx-0011'
    and chng_type = 'C'
    group by ssn, chng_type,tran_id;
    It returns a 'C' chng_type but it is not the last one. when I query on this ssn this is what I get:
    ssn tran_id chng_type
    xxx-xxx-0011 001 A
    xxx-xxx-0011 002 E
    xxx-xxx-0011 003 C
    xxx-xxx-0011 004 S
    xxx-xxx-0011 005 C
    xxx-xxx-0011 006 T
    I only want to return the ssn's with a last transaction chng_type of 'C'. How can I get the correct information returned. Please advise.

    From what I see and read... there is one to many group by
    You wrote
    select ssn, max(tran_id), chng_type,tran_id
    from pda_tran
    where ssn = 'xxx-xxx-0011'
    and chng_type = 'C'
    group by ssn, chng_type,tran_id;
    If you want the max(tran_id), remove it from the "group by"
    select ssn, chng_type, max(tran_id)
    FROM
    (SELECT 'xxx-xxx-0011' ssn, '001' tran_id, 'A' chng_type FROM DUAL UNION
    SELECT 'xxx-xxx-0011' ssn, '002' tran_id, 'E' chng_type FROM DUAL UNION
    SELECT 'xxx-xxx-0011' ssn, '003' tran_id, 'C' chng_type FROM DUAL UNION
    SELECT 'xxx-xxx-0011' ssn, '004' tran_id, 'S' chng_type FROM DUAL UNION
    SELECT 'xxx-xxx-0011' ssn, '005' tran_id, 'C' chng_type FROM DUAL UNION
    SELECT 'xxx-xxx-0011' ssn, '006'tran_id, 'T' chng_type FROM DUAL )
    where ssn = 'xxx-xxx-0011'
    and chng_type = 'C'
    group by ssn, chng_type;

  • V v urgent ...  how to get the selected rows in the vl02n transaction

    Hi ,
    I have requirement that i have selected the line items in the vl02n transaction.
    If I select only one row there is option gs_get_cursor-line.
    If I select more than one line item at a time I am getting only the last value in to gs_get_cursor-line.
    Can anybody let me know how to get the multiple line items  that are selected
    It is very urgent ..
    Plz Help

    Hi,
    can you check the E_row_id .
    v_row type LVC_S_ROW
    read table itab index E_ROW-index.
    regards,
    Ajay
    Edited by: Ajay on Feb 14, 2008 6:22 PM

  • How to display the last row in a table

    I have a table that is constantly updating, and I always want to see the last row. How can I get my table to auto scroll?

    Hi žabić,
    there is a property called "top left visible row". You can use it to scroll your table.
    edit:
    Maybe this is not the exact name, but you can see an example here
    Mike
    Message Edited by MikeS81 on 05-27-2010 03:57 PM

Maybe you are looking for

  • Import json file to sql server

    I have 1000 records in text file. My requirement is to insert data into sql server. For that, if i can convert to xml or push to script component also fine. Text file consists in this format... [{"ID":1,:"Name":"test1","State":"AP"},{"ID":2,:"Name":"

  • Screan keeps going black while it is on

    have a hp 2009m monitor it wont stay lit up turn it on stays on 2 seconds then goes black turn it off and back on again and it comes back on again for 2 more seconds then goes black again  does any one  knows what the problem might be thanks         

  • Payment Method Required - MIRO and MIR7

    We need to make the Payment Method Required for Logistics Credit Memo's.  If possible we would also like to customize the error/warning message when the user leaves out a Payment Method. Thank you, David Tanner

  • How a client could retrieve interested data from log file in dbxml?

    I have heard about db_printlog utility in BDB. Is there any similar utility (like shell command or API) in bdbxml?. I want to extract updated nodes from log file.

  • I'm having problems installing disk 2 of oracle 9iAS linux edition

    I'm having problems installing disk 2 of oracle 9ias linux edition is thier anyone else having this same problem