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!
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 -
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 retrivedAll
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 -
Trying to get the last row from a resultset
Hi,
I'm trying to do a query to postgreSQL and have it return the last updated value, (last row).
My prepared statement is returning the correct results, but i'm having a problem getting the latest value.
I'm using a comboBox to drive a textfield, to load the last entered values in depending on which item in the comboBox is selected.
I've tried a variety of things and most seem to return the first row, not showing the updated values.
Or, if it does work, it takes to long to load, and i get an error.
here is the working code;
Object m = machCBX.getSelectedItem():
try { PreparedStatment last = conn.prepareStatement("SELECT part, count FROM production WHERE machine = ?",
ResultSet.TYPE_SCROLL_INSENSITIVE, //tried both INSENSITIVE and SENSITIVE
ResultSet.CONCUR_READ_ONLY);
last.setString(1, String.valueOf(m));
rs. = last.executeQuery();
if(rs.isAfterLast) == false ) {
rs.afterLast();
while(rs.previous()) {
String p = rs.getString("part");
int c = rs.getInt("count");
partJTX.setText(p);
countJTX.setText(c);
}this grabs values, but they are not the last entered values.
Now if i try to use rs.last() it returns the value i'm looking for but takes to long, and i get:
Exception in thread "AWT-EventQueue-0" java.lang.OutOfMemoryError: Java heap space I also know using ra.last() isn't the best way to go.
I'm just wondering if there is another way other than getting into vectors and row count? or am i better off to go with the later?
thanks
-PDOK, you've got a major misunderstanding...
The relational database model is built on the storage of sets - UNORDERED sets. In other words, when you hand a database a SELECT statement without an ORDER BY clause, the database is free to return the results in any order.
Now it so happens that most databases will happen to return data retrieved by an unordered SELECT, at least for a while, in the same order that it was inserted, especially if no UPDATE or DELETE activity has occured, and no database maintenance has occured. However, eventually most tables have some operation that creates a "space" in the underlying storage, or causes a row to expand and have to be moved or extended, or something. Then the database will start returning unordered results in a different order. If you (or other people) never ever ever UPDATE or DELETE a table, then on some databases the data might well come out in insertion order for a very very long time; given human nature and the way projects tend to work, relying on that is a sucker's bet, IMHO.
In other words, if you want the "most recent" something, you need to store a timestamp with your data. (With some databases, you might be able to take advantage of some non-standard feature to get "last updates" or "row change timestamps", but I know of no such for Postgres.
While this won't solve your major problem, above, your issue with rs.last is probably occuring because Postgres by default will prefetch your entire ResultSet. Use Statement.setFetchSize() to change that (PreparedStatement inherits the method, of course). -
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 jbsJDBCServletI 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 AMHi, 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?
StephenYou 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
KevinHi,
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.brHi 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.
RegardsHi
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/2011vitaly87 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 HelpHi,
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
Maybe you are looking for
-
Can I drag and drop single photos into Events?
Hi guys. I've very recently ordered a new Mac that will have iLife 08 on it. Before I get started with it I've got a question about Events. I've been using iPhoto for the last several years, organizing my photos into albums. I've cleaned up my images
-
Hi, We are using Oracle BI Publisher 10.1.3.4.1 deployed with in Oracle application server SOA suite 10.1.3.1.0 on its own. We plan to upgrade our application server area to WEBLOGIC suite some time soon. Finally, we want to deploy Oracle BI Publishe
-
Online fraud, can somebody help me?
I have doing something stupid on webcam and he/she asking money from me what should i do now? Here is the conversataion not sure what to do right now [2014-05-05, 11:08:38 PM] jenny ming: haha you **bleep** [2014-05-05, 11:08:56 PM] jenny ming: did
-
Font source path and vendor id
two questions 1. Since the step from 1.4 to 1.5 my old font folder is no more accepted by MakeOTF. It stops compiling the font by the status "Running txlib...". Him - I downloaded the examples and all works fine. So I`d copied my fonts paths into the
-
Message from the Dreamweaver Product team
Now that the October release is out, we have collected significant feedback from our users. Based on the feedback, we would like to share our thinking in terms of the short/mid-term road-map of the product. We are currently focused on the following v