Counting Rows from a ResultSet

Hi!
If I retreive some information from a database, say by using:
ResultSet RS = Stmt.executeQuery("select * from events");How can I get a value for the amount of rows in this ResultSet?
Thanks!
Alastair

Almost everyone, when they first use ResultSet thinks of it as a container with the data rows already in there, and wonders why there's no size method.
But that's not how they work. A ResultSet, generally, holds only one row at a time. next requests the next row from the database and before next is called the ResultSet doesn't know if another row is going to be available. Indeed the number of rows that qualify for return in the result set may actually change while you are processing it.
Doing the SELECT COUNT(*) request asks the database for the number of rows that match any criteria in the SELECT, but that number may have changed when you actually retrieve the rows. Someone else may have added or removed rows.

Similar Messages

  • Can i count row from ResultSet ?

    I would like to count row from ResultSet for
    take it into my array object because i must know number of row before create array object.
    Example:
    ResultSet rset = stmt.executeQuery("select * from user ");
    /*i = amount of ResultSet*/
    User[] user = new User;
    int l=0;
    while (rset.next()){
    user[l] = new User();
    user.name = rset.getString(1);
    l++;

    Hi,
    As per my knowledge there is no method by which you can get the count of items in a resultset directly. You will have to loop through the reseltset and set a variable for count. In your specific case I would advise you to use a Vetor instead of an array so that you need not bother about the size.
    ResultSet rset = stmt.executeQuery("select * from user ");
    Vector user = new Vector();
    while (rset.next()){
    user.addElement(rset.getString(1));
    Now you will have a Vector that holds the user info. To retrieve the user info loop through the Vector.
    for (int i; i<user.size(); i++){
    userName = user.elementAt(i);
    Hope I was of some help.
    cheers!!!
    Nish

  • Count rows from several tables

    hello,
    im trying to count row from multiple tables
    for example i need the select statement to produce the following
    table_name count
    table1 5
    table2 6
    table3 3
    i came up with the following script but it counts the number of tables i have
    select object_name, (select count(*) from user_tables where table_name = object_name) from all_objects
    where object_type = 'TABLE'

    Manik wrote:
    May be possible:
    Check this:
    SELECT table_name,
    TO_NUMBER (
    EXTRACTVALUE (
    xmltype (
    DBMS_XMLGEN.getxml ('select count(*) c from ' || table_name)),
    '/ROWSET/ROW/C'))
    COUNT
    FROM (select * from all_tables where table_name in ('TABLE1','TABLE2'))
    WHERE owner = 'SCOTT';Cheers,
    Manik.Awesome Manik... Just too good. Thanks.
    I wish i could have given you the 'Correct' points. ;-)
    Can you please explain the logic in brief? Will be helpful for everybody to understand...

  • Count rows from multiple tables using SQL only

    Hi, I know this has probably been answered before, but I couldn't find the answer anywhere. Please help.
    I'd like count(*) [rows] for all tables in database using SQL only - no PL/SQL
    The result should be something like:
    Table RowCount
    DBA_TABLES 1000
    DBA_USERS 50
    etc.
    Thanks!

    offcource write this script:
    create or replace procedure count_tables (ip_schema VARCHAR2)
    is
    lv_owner VARCHAR2(100);
    lv_table_name VARCHAR2(100);
    lv_sql_statement VARCHAR2(2000);
    lv_count_table NUMBER;
    CURSOR c1 IS
    SELECT owner, table_name
    FROM all_tables
    WHERE owner = ip_schema
    ORDER BY table_name;
    begin
    dbms_output.put_line ('+--------------------------------------------------------------------+');
    dbms_output.put_line ('¦ | | ¦');
    dbms_output.put_line ('¦ Schema Name | Table Name | Number of Rows ¦');
    dbms_output.put_line ('¦ | | ¦');
    dbms_output.put_line ('¦------------------------------------------------------------------¦');
    OPEN c1;
    LOOP
    FETCH c1 INTO lv_owner , lv_table_name;
    EXIT WHEN c1%NOTFOUND;
    lv_sql_statement := 'SELECT count(*) FROM ' || lv_owner || '.' || lv_table_name;
    EXECUTE IMMEDIATE lv_sql_statement INTO lv_count_table;
    IF lv_count_table > 0 THEN
    dbms_output.put_line ('| '||rpad(lv_owner, 14, ' ')||'| '|| rpad(lv_table_name, 32, ' ')||'| '|| rpad(lv_count_table, 16, ' ')||' |');
    -- dbms_output.put_line ('|---------------|---------------------------------|------------------|');
    END IF;
    END LOOP;
    CLOSE c1;
    dbms_output.put_line ('+--------------------------------------------------------------------+');
    exception
    WHEN OTHERS THEN
    dbms_output.put_line ('owner: '||lv_owner||' - table: '||lv_table_name||' - '||sqlerrm);
    end count_tables;
    set serveroutput on size 1000000
    exec count_tables
    drop procedure count_tables;

  • Any way to count rows from function

    I have the function: pkgcustomer.get(id).
    To count the rows from this function I do:
    select count(*)
    from
      (select pkgcustomer.get(2)
      from dual);So, this gives me 1.
    The id '2' exist
    When I give an id that does nog exist (for example 5999), I also get '1' for the rows he count.
    Can someone help me to get the correct count from a function?
    I also did:
    OPEN c_testresult FOR 'SELECT pkgcustomer.get(2) FROM DUAL;';
              LOOP
                FETCH c_testresult INTO rec_testresult;
                EXIT WHEN c_testresult%NOTFOUND; 
                l_counter         := l_counter + 1;
              END LOOP;
              l_testresult        := to_char(l_counter);
            CLOSE c_testresult;I hope that someone can help me...
    Regards

    > And what if I do the function: pkgcustomer.get(5999)? 5999 is not an existing ID, so this
    should me give 0, but when I do: select pkgcustomer.get(5999) from dual, I also get 1.
    Can you count?
    Okay then. The function returns a value. You are counting the number of values the function returns, right?
    Q. The function returns the number zero. How many values does it return?
    A. One!
    Q. The function returns the number one. How many values does it return?
    A. One!
    Q. The function returns the number 7293273948438727632192378643 . How many values does it return?
    A. One!
    Now if you still fail to grasp this, I seriously suggest you rethink the career choice you've made. Not everyone can be software developers, just like not everyone can be scientists, firefighters, chefs etc.

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

    OK, 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).

  • Deleting a row from a resultSet with nulls

    Hello All,
    I have stumbled across a bit of a problem when using a cachedRowSet
    If I select columns from my database that have null values, and I call deleteRow() I get a
    NullPointerException.
    at com.sun.rowset.internal.CachedRowSetWriter.deleteOriginalRow
    However if I don�t select the null columns in my cachedRowSet. I can delete no worries.
    I would of though that the cachedRowSet object could handle nulls but it seems it doesn�t, anyone know any workarounds for this?
    NOTE: using JTDS driver would that play a part?

    If I select columns from my database that have null
    values, and I call deleteRow() I get a Does the whole row a null record ?
    Please put a sample program so that the problem can be reproduced.
    >
    NullPointerException.
    at
    com.sun.rowset.internal.CachedRowSetWriter.deleteOrigi
    nalRow
    Also give the stack trace.

  • Counting rows in a ResultSet, help please?

    sorry there was a type error
    how to count the number of rows in a resultser object which may contains millions of rows? besides using a while loop? thanks

    You can do rs.last() then get the number of rows using rs.getRow() but as the previous poster hinted at this will take very long time with a lot of records as they all have to be retrieved before the rs.last() method can complete.

  • Getting the first row from a ResultSet??

    I have a query that returns a set of values but am interested only in the first value.How can I get that. I tried to use getArray method but that gives a "java.sql.SQLException: Exhausted Resultset".
    Any suggestions??

    I think I'm having the same problem with you.
    this is my method:
    private Vector getData( ResultSet rs){
    String str = "";
    try{
    while( rs.next() ){
    str = rs.getString( 1 );
    rows.addElement( str );
    }catch( SQLException sqlex ){
    sqlex.printStackTrace();
    return rows;
    I don' t know if you meant this.hoping this can help you

  • Getting the no. of rows returned from the resultset

    Could somebody tell how can I get the count of rows from the resultset object.
    Thanks a lot in advance

    hmmm 20,710 topics and 69,000 odd posts and no one has EVER asked this question before.. it's a miracle....
    or maybe it has been asked and dealt with approx... 11,000 times.
    here is a discussion from 1998 for example http://forum.java.sun.com/thread.jsp?forum=48&thread=83958

  • Returning a subset of rows through a ResultSet WITHOUT rownum?

    I am trying to figure out a way to get a subset of rows from a ResultSet (or ResultSet equivalent) without using rownum and without sending all the rows before the requested row over the wire.
    My problem is this: I am not in control of the SQL that is sent to the database. It is autogenerated by a third party tool (TOPLink). Therefore using the rownum solution isn't practical. My steps of operation are:
    1. Get SQL from TOPLink
    2. Pass SQL through a Statement
    3. Get resulting ResultSet
    At this point, I want to say, "Mr. ResultSet, I only want rows 200-250." And I then want Mr. ResultSet to fetch only rows 200 to 250, and no others. I don't want to see rows 1 to 199 coming over the wire.
    Anyone have any ideas? Is this possible at all? Also, if there's a way to do this through the TOPLink mechanisms (ScrollableCursors and ReportQuery objects and whatnot), please do let me know. I have tried using the TOPLink facilities, and sure enough rows 1 to 199 flow across the network.
    Thanks,
    Michael Allen
    [email protected]

    Hi Michael,
    Is there some sort of selection criteria in which you could use return the required 200-250 rows of data? If so, I would embed that into the TopLink query.
    Another option is using the ORDER BY operator. Without order, constructing a query of elements 200-250 twice would not guarentee that they would be the same elements.
    You can also construct your own SQL statement and execute it directly on a TopLink session.
    Darren Melanson
    Strategic Implementation Consultant
    Oracle Canada.
    I am trying to figure out a way to get a subset of rows from a ResultSet (or ResultSet equivalent) without using rownum and without sending all the rows before the requested row over the wire.
    My problem is this: I am not in control of the SQL that is sent to the database. It is autogenerated by a third party tool (TOPLink). Therefore using the rownum solution isn't practical. My steps of operation are:
    1. Get SQL from TOPLink
    2. Pass SQL through a Statement
    3. Get resulting ResultSet
    At this point, I want to say, "Mr. ResultSet, I only want rows 200-250." And I then want Mr. ResultSet to fetch only rows 200 to 250, and no others. I don't want to see rows 1 to 199 coming over the wire.
    Anyone have any ideas? Is this possible at all? Also, if there's a way to do this through the TOPLink mechanisms (ScrollableCursors and ReportQuery objects and whatnot), please do let me know. I have tried using the TOPLink facilities, and sure enough rows 1 to 199 flow across the network.
    Thanks,
    Michael Allen
    [email protected]

  • I need a resultset with 10 rows from dual

    Which is the easiest SELECT I have to write, when the question is: "I need a resultset with 10 rows from dual"
    one solution is
    SELECT 'X' FROM EMP WHERE ROWNUM <= 10;
    problem: if emp has fewer than 10 rows, I have an incorrect resultset
    another problem: if I need 1000 and not 10 dummy-rows, than is emp definitely the wrong way, because the default-emp table has only 14 rows.
    Is there an easy generic solution for this problem? If I need only one row, Oracle has the workaround with the DUAL-table.

    What about this new method (dedicated by me to this great FORUM!). It is easy to use, easy to understand, and very fast:
    SQL> set echo on
    SQL> set timing on
    SQL> select rownum
      2    from all_objects
      3   where rownum <=10;
        ROWNUM
             1
             2
             3
             4
             5
             6
             7
             8
             9
            10
    10 rows selected.
    Elapsed: 00:00:00.00
    SQL> select COUNT(rownum)
      2    from all_objects
      3   where rownum <=1000;
    COUNT(ROWNUM)
             1000
    Elapsed: 00:00:00.00
    SQL> with r1000
      2  as (select rownum
      3        from all_objects
      4        where rownum <=1000)
      5  select count(rownum)
      6    from r1000, r1000
      7   where rownum <= 1000000;
    COUNT(ROWNUM)
          1000000
    Elapsed: 00:00:00.05 -- !for 1 million numbers!
    SQL> with r1000
      2  as (select rownum
      3        from all_objects
      4        where rownum <=1000)
      5  select count(rownum)
      6    from r1000, r1000, r1000
      7   where rownum <= 10000000;
    COUNT(ROWNUM)
         10000000
    Elapsed: 00:00:04.09  -- !for 10 millions numbers!

  • Count of rows from different tables.

    Hi Friends,
    I have 4 tables with a common column name "ID". I would like to get the count of rows from all the four tables which has the same ID.
    Ex
    select count(a.id) from table1 a,table2 b,table3 c,table4 d where a.id=b.id=c.id=d.id=5;
    please suggest me some solution

    may be thsi?
    select count(a.id) from table1 a,table2 b,table3 c,table4 d
    where a.id=b.id and a.id=c.id and a.id=d.id and a.id=5;

  • Retrieving the entire row from ResultSet

    Hi All,
    I am using SQL database and wants to get the data from tables as rows instead of columns. Please let me know if any of you know how to retrieve the rows from table using ResultSet.
    Thanks.

    you would need a loop like this:
    for( int i = 0; i < resultset.getMetadata().getColumnCount(); i++ )
      System.out.print( resultSet.getXXX( i ) );
    }That will print out the row

  • Counting the rows in a ResultSet

    I am wondering how I could find out the number of rows in a ResultSet after performing a query?

    In case anyone's curious I figured out the problem. The ResultSet needs to be set to move forward AND backward. This is done as follows:
    Statement stmt = conn.createStatement(
                             ResultSet.TYPE_SCROLL_INSENSITIVE,
                                  ResultSet.CONCUR_READ_ONLY);

Maybe you are looking for

  • Trouble opening reader?

    When I try to open reader, I have a blank screen.  The download tells me it has been successful.  Can someone help me with this problem - I can't figure out what I'm doing wrong. Thanks

  • Osx 10.5.8 crashes windows 7

    When my dual g5 power mac running 10.5.8 and my wife's acer laptop running window 7 are both connected to my wireless network, windows crashes hard.  Static screen, and loud buzzing from speakers.  Unresponsive, requiring power button restart, or it

  • Trigger for invoice creation after POD Entry

    Hi, Is anyone familiar with the process surrounding POD? In BW, I am trying to extract to the POD time & date, but it looks as if thats impossible as it only sits in the change header. AEDAT holds the date, but AEDAT cannot be relied on as the only d

  • JNI via Server-Side Language

    I'd like to use the following post as a reference: http://72.5.124.102/thread.jspa?threadID=788137&messageID=4479784 "The DLL will remain loaded between calls, so if you use a global variable to store the connection then it should be ok. " Of course

  • Files from Photoshop CC 2014 slows/crashes InDesign CS 6

    Placing images edited in Photoshop CC 2014 into InDesign CS 6 takes minutes, trying to create a PDF hangs up InDesign.