Random Row From ResultSet

Hi, i need some help on this:
First, my JSP will query a database table and return a resultset that contains a lot of records. Is there a way to randomly choose ONE of the record from resultset ?
Number of records return by the resultset is dynamic (always change), so, is there a way to store all the records into array first?
Or do you have any other suggestions ?
Thank you !

Better way is to create a Bean for the row returned by the Result Set. For example your result set return 2 columns i.e. ID and Name then your bean should have getter and setter methods for the columns and repeating the loop for the Result set store each returned row in the bean and then store this bean in the Collection. This is better way to work with it.

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

  • How to efficiently select random rows from a large table ?

    Hello,
    The following code will select 5 rows out of a random set of rows from the emp (employee) table
    select *
      from (
           select ename, job
             from emp
           order by dbms_random.value()
    where rownum <= 5my concern is that the inner select will cause a table scan in order to assign a random value to each row. This code when used against a large table can be a performance problem.
    Is there an efficient way of selecting random rows from a table without having to do a table scan ? (I am new to Oracle, therefore it is possible that I am missing a very simple way to perform this task.)
    thank you for your help,
    John.
    Edited by: 440bx on Jul 10, 2010 6:18 PM

    Have a look at the SAMPLE clause of the select statement. The number in parenthesis is a percentage of the table.
    SQL> create table t as select * from dba_objects;
    Table created.
    SQL> explain plan for select * from t sample (1);
    Explained.
    SQL> @xp
    PLAN_TABLE_OUTPUT
    Plan hash value: 2767392432
    | Id  | Operation           | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT    |      |   725 | 70325 |   289   (1)| 00:00:04 |
    |   1 |  TABLE ACCESS SAMPLE| T    |   725 | 70325 |   289   (1)| 00:00:04 |
    8 rows selected.

  • 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

  • Removing Duplicate Rows from resultSet

    I have a query pulling data from 5 tables in 12 columns. I have rows where all of the data is duplicated with the exception of one date column. How would I go about deleting rows that are duplicates with the exception of this one column? I still need to pull the date from the date column with the Max(date).
    i.e.
    Bob Smith 1 2 3 4 12-Jul-2006
    Bob Smith 1 2 3 4 02-Aug-2006
    Bob Smith 1 2 3 4 21-Jan-2006
    Form this resultset I only want one row
    Thanks.

    this example might be of help.
    SQL> select * from employees;
    YEAR EM NAME       PO
    2001 02 Scott      91
    2001 02 Scott      01
    2001 02 Scott      07
    2001 03 Tom        81
    2001 03 Tom        84
    2001 03 Tom        87
    6 rows selected.
    SQL> select year, empcode, name, position,
      2         row_number() over (partition by year, empcode, name
      3                            order by year, empcode, name, position) as rn
      4    from employees;
    YEAR EM NAME       PO         RN
    2001 02 Scott      01          1
    2001 02 Scott      07          2
    2001 02 Scott      91          3
    2001 03 Tom        81          1
    2001 03 Tom        84          2
    2001 03 Tom        87          3
    6 rows selected.
    SQL> Select year, empcode, name, position
      2    From (Select year, empcode, name, position,
      3                 row_number() over (partition by year, empcode, name
      4                                    order by year, empcode, name, position) as rn
      5            From employees) emp
      6   Where rn = 1;
    YEAR EM NAME       PO
    2001 02 Scott      01
    2001 03 Tom        81
    SQL> Delete From employees
      2   Where rowid in (Select emp.rid
      3                     From (Select year, empcode, name, position,
      4                                  rowid as rid,
      5                                  row_number() over (partition by year, empcode, name
      6                                            order by year, empcode, name, position) as rn
      7                             From employees) emp
      8                    Where emp.rn > 1);
    4 rows deleted.
    SQL> select * from employees;
    YEAR EM NAME       PO
    2001 02 Scott      01
    2001 03 Tom        81
    SQL> if you can post a sample create tables and data it will help us provide you a some solutions.

  • Help :add multiple rows from Resultset to ArrayList ?

    My query returns one column and multiple rows. In Java code , I am trying to get this data in array or arraylist through ResultSet
    ex:
    item_num
    p001
    p002
    p003
    when I print, it only gets the item in the first row.
    ArrayList myArrayList = new ArrayList();
    resultset = preparedstatement.executeQuery();
    if (resultset.next())
    myArrayList.add(new String(resultset.getString("item_num")));
    Print:
    for (int j = 0 ; j < myArrayList.size() ; j++ )
    System.out.println((String)myArrayList.get(j)); --this prints only the first item.
    can someone assist ?

    changing if to while fixed it.

  • Accessing and comparing rows from resultset

    Post Author: pross
    CA Forum: Formula
    I am a newbie, and this might be a simple answer ( I hope so)
    I would like to compare rows inside my result set. For example, if I recieve information such as:
    CUSTOMER:12345 AMOUNT:100.00 CUSTOMER:12345 AMOUNT(100.00) CUSTOMER:2345 AMOUNT:75.00 CUSTOMER:4567 AMOUNT:25.00
    I want to be able match the same customer number and amounts that balance out &#91; 100.00 and (100.00)&#93;, to not show in my report.
    How can I do this?
    Thanks                    

    Post Author: pross
    CA Forum: Formula
    I am returning rows that match my criteria. Because of the way the data is stored, it shows a record that has a positive value (a charge) and a negative value for the same criteria (a payment). I want to only show records that do not have a negative value, as well as the record that shows the charge for that record. For instance I want to be able to match everything in my row as well as the amounts from those two rows sum to 0. I am not sure how to do this in a sql query or be able to filter it out in CR.

  • Output displaying last row from resultset

    I have a class called user, which has only first, last name and email. I have a method in a UserDB class that reads a database and puts the results into the user class, then stores each user object in a vector. I know there are only 3 records, and my display is only showing the last record 3 times. I can't figure out what I am doing wrong.
    UsersServlet - calls the readRecord method and creates the vector to be stored in a session
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
              MurachPool connectionPool = MurachPool.getInstance();
              Connection connection = connectionPool.getConnection();
              Vector user = UserDB.readRecord(connection);
              HttpSession session = request.getSession();
              session.setAttribute("users", user);
              RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/user11/users.jsp");
            dispatcher.forward(request, response);
         }UserDB class - read record method.
    public static synchronized  Vector readRecord(Connection connection)
              User user = new User();
              Vector vector = new Vector();
              try{
                        String sql = "SELECT * FROM User ";
                        Statement statement = connection.createStatement();
                        ResultSet rs = statement.executeQuery(sql);
                        while(rs.next())
                             user.setFirstName(rs.getString("FirstName"));
                             user.setLastName(rs.getString("LastName"));
                             user.setEmailAddress(rs.getString("EmailAddress"));
                             vector.addElement(user);
                        return vector;
              }catch(SQLException e){
                   return null;
         }The jsp display page.
    <% java.util.Vector users = (java.util.Vector)session.getAttribute("users");
       for (int i =0; i<users.size(); i++){
          business.User user = (business.User)users.get(i);
          %>
      <tr valign="top">
        <td><p><%= user.getFirstName() %></p></td>
        <td><p><%= user.getLastName() %></p></td>
        <td><p><%= user.getEmailAddress() %></p></td>
         <td><p><%= i %></p></td>
        <td><a href="/user11/ShowUserServlet?emailAddress=<%=user.getEmailAddress()%>">Update</a></td>
        <td><a href="/user11/DeleteUserServlet?emailAddress=<%=user.getEmailAddress()%>">Delete</a></td>
      </tr>
      <%}%>

    A Vector is really an array of pointers. When you add the same User object to the vector several times you are adding many pointers to the same object. In this program you want several User objects, so you need to create a new one each iteration of the loop.
    You'll also need to close the ResultSet, Statement and Connection. Preferably in a finally statement.

  • Thin JDBC Driver is missing some rows from resultset

    Hi All
    I am faced with a peculiar problem.
    When I fire a SQL query using Toad, I get correct results but firing the same query using JDBC Driver - ojdbc14.jar (ORacle 11g R1) - we are getting lesser number of records.
    Our SQL pulls around 300k of records and buckets them based on some column value into different chunks. We use NTILE function and it shows right results in TOAD.
    Using same sql with JDBC, We are losing 100 rows per bucket.
    Any ideas?
    SQL is
    SELECT
    T.CTLG_ITM_ID as catalogItemIds,
    T.INV_STAT_TYP_ID,
    T.OORD_DT,
    T.LST_UPDT_DTTM,
    T.CTLG_ITM_SELL_TYP_ID,
    P.OORD_IND,
    C.BKORD_ELIG,
    NTILE(300) over (ORDER BY T.CTLG_ITM_ID) AS bucketId
    FROM
    INV_STAT_ROLLUP_T T,
    PRD_T P,
    CTLG_T C,
    CTLG_TREE_PATH_T TP
    WHERE
    T.CTLG_ITM_ID = TP.CTLG_ITM_ID AND
    TP.PAR_CTLG_ITM_ID = P.CTLG_ITM_ID AND
    C.BRD_CD = '10'
    As per toad, each bucket should get us 1038 records but Thin JDBC Driver is fetching us only 898 records.
    Any idea why this discrepancy?
    Thanks
    Saroj

    rozdev29 wrote:
    When I fire a SQL query using Toad, I get correct results but firing the same query using JDBC Driver - ojdbc14.jar (ORacle 11g R1)Seeing the downloads page:
    http://www.oracle.com/technetwork/database/enterprise-edition/jdbc-111060-084321.html
    There IS no ojdbc14.jar for Oracle 11g. The minimum is Java 5. So correct me if I'm wrong, but you seem to be using a very old driver here. I would try a newer one if I were you.

  • Returning Random Row based on Subset of Data within Table

    Hi,
    Please see below.  Running SQL Server 2008 R2.
    Sample DDL:
    CREATE TABLE [dbo].[TestPersons]
    [TestPersonID] [int] NOT NULL IDENTITY(1,1),
    [FirstName] [varchar](50) NULL,
    [LastName] [varchar](50) NULL,
    [AreaID] [varchar](50) NULL,
    CONSTRAINT [PK_TestPersons_TestPersonID] PRIMARY KEY CLUSTERED ([TestPersonID] ASC)
    WITH
    PAD_INDEX = OFF,
    STATISTICS_NORECOMPUTE = OFF,
    IGNORE_DUP_KEY = OFF,
    ALLOW_ROW_LOCKS = ON,
    ALLOW_PAGE_LOCKS = ON
    ON [PRIMARY]
    ON [PRIMARY]
    GO
    Sample Data:
    INSERT INTO
    [dbo].[TestPersons] ([FirstName], [LastName], [AreaID])
    VALUES
    ('Carlos', 'Matlock', 'A0009'),
    ('William', 'Rivas', 'A0001'),
    ('Kathryn', 'Rice', 'A0008'),
    ('John', 'Ball', 'A0009'),
    ('Robert', 'Barnhill', 'A0009'),
    ('Timothy', 'Stein', 'A0009'),
    ('Christopher', 'Smith', 'A0001'),
    ('Brian', 'Speakman', 'A0001'),
    ('Harold', 'Clark', 'A0009'),
    ('Tim', 'Henson', 'A0009'),
    ('Victor', 'Chilson', 'A0009')
    The above insert statement is a small example of the data contained in this table.  Normally the table would contain several thousand rows.  We use the following query to replace actual data with random rows from our test table:
    UPDATE
    [P]
    SET
    [P].[FirstName] = [T].[FirstName],
    [P].[LastName] = [T].[LastName],
    [P].[AreaID] = [T].[AreaID]
    FROM
    [dbo].[Persons] [P]
    INNER LOOP JOIN
    [dbo].[TestPersons] [T] ON ([T].[TestPersonID] = (1 + ABS(CRYPT_GEN_RANDOM(8)%5000)))
    This query works as it selects a random row from the entire set of data in the table.  However there are cases where we need to specify a restricted subset to randomize from.  For example, we may need to randomize data only for Persons with an AreaID
    of A0001 or A0008.  So in that case, and using the sample data above, we would want the  randomization to only select from rows in TestPersons that have an AreaID of A0001 or A0008.  How would I go about accomplishing this?  I've tried
    adding a WHERE clause but it seems it's ignored because of the INNER LOOP JOIN.  I've also tried including [P].[AreaID] = [T].[AreaID] in the join hint but to no avail.
    I also realize having sample data with only the set that we need would solve this problem but for our needs we need a large test set as our randomization requirements depend on the situation.
    Any assistance is greatly appreciated!
    Best Regards
    Brad

    DECLARE @TestPersons TABLE (TestPersonID int NOT NULL IDENTITY(1,1), FirstName varchar(50), LastName varchar(50), AreaID varchar(50))
    INSERT INTO @TestPersons (FirstName, LastName, AreaID)
    VALUES ('Carlos', 'Matlock', 'A0009'), ('William', 'Rivas', 'A0001'), ('Kathryn', 'Rice', 'A0008'), ('John', 'Ball', 'A0009'), ('Robert', 'Barnhill', 'A0009'), ('Timothy', 'Stein', 'A0009'),
    ('Christopher', 'Smith', 'A0001'), ('Brian', 'Speakman', 'A0001'), ('Harold', 'Clark', 'A0009'), ('Tim', 'Henson', 'A0009'), ('Victor', 'Chilson', 'A0009')
    ;WITH subset AS (
    SELECT ROW_NUMBER() OVER (ORDER BY TestPersonID) AS sID, *
    FROM @TestPersons
    WHERE FirstName LIKE '%e%'
    SELECT *
    FROM subset
    WHERE sID = round((((SELECT COUNT(*) FROM subset) - 1 - 1)*rand())+1,0)
    This will grab a random row from a subset (defined in the CTE).

  • Select a fixed number of random rows

    Hi,
    I just would like to select a fixed number of random rows from a table. That is, I would like to get 5 rows, without specifying the row_id, and the selected rows should "always" be different. Just as picking 5 balls out of a big box (which is filled with many balls).
    Is there a way to easily put it into one sql statement or do I have to write a workaround in the programming language I use?
    Thanks a lot in advance,
    CQ

    AskTom has a discussion on this:
    http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:6075151195522
    Note that it requires that you
    1) Generate a random number for every row in the table
    2) Sort the table by those random numbers
    which is a significant performance hit if the table is large.
    Justin

  • Select Random Rows in PL/SQL

    I would like to know if anyone has a suggestion fora select statement that would select random rows from a table based on the following:
    The table contains 1-to-many categories. From each of these categories I need to select a 'x' amount of rows based upon the category id, with a total of 25 rows being selected overall. Some categories will have only 1 row selected, some will have more than 1. The rows selected contain questions that are either multiple choice (type=1) or true/false (type=2). The total rows selected (25) cannot contain more than 20% of true/false questions. Anyone have a solution for a select statement? Thanks.

    Not having a database at hand. To be treated as a template
    with
    parameters as
    (select all_rows,
            all_categories,
            :all_questions all_questions,                               -- your 25
            :category_questions category_questions,                     -- your 'x'
            ceil(all_categories / :category_questions) pick_categories,
            :type_2_percentage type_2_percentage                        -- your 20% expressed as 0.2
       from (select count(*) all_rows,
                    count(distinct category) all_categories,
               from your_table
    categories_scrambled as
    (select category,dense_rank() over (order by categories_mix) category_choice
       from (select category,
                    ceil(dbms_random.value(0,1000)) categories_mix
               from your_table
              group by category
    rows_scrambled as
    (select category,question_type,question_text,dense_rank() over (order by rows_mix) row_choice
       from (select category,question_type,question_text,
                    ceil(dbms_random.value(0,10000)) rows_mix
               from your_table
    combination as
    (select r.category,r.question_type,r.question_text,r.row_choice,c.category_choice,
            row_number() over (partition by r.row_choice,r.question_type order by r.row_choice) row_mark
       from rows_scrambled r,categories_scrambled c
      where r.category = c.category
    type_2_questions as
    (select question_text,question_type,category
       from combination
      where category_choice <= (select pick_categories from parameters)
        and row_mark <= floor(:all_questions * :type_2_percentage / (select pick_categories from parameters))
        and question_type = 2
    type_1_questions as
    (select question_text,question_type,category,row_number() over () the_count
       from combination
      where category_choice <= (select pick_categories from parameters)
        and row_mark <= ceil((:all_questions - (select count(*) from type_2_questions)) / (select pick_categories from parameters))
        and question_type = 1
    select question_text,question_type,category
      from type_2_questions
    union all
    select question_text,question_type,category
      from type_1_questions
    where the_count <= :all_questions - (select count(*) from type_2_questions)Regards
    Etbin

  • How to select a random row with for update?

    Hi,
    I have a package that needs to assign a random, reusable number (ID) that is not currently being used - to a procedure.
    I'm trying to simulate a pool of numbers (IDs) using a table that has an ID and IS_USED columns.
    How do I do:
    select a random ID (random row)
    from pool_table
    where IS_USED is 0 (not taken)
    FOR UPDATEThe for update is to lock the row from being taken by another process calling the package.
    OR:
    Can I simulate a pool of numbers with a different object (not a table)?
    I need the numbers to be coherent between sessions (thus package variables will not work) and only one session uses the same ID at any given time. When it finishes the number becomes available for further runs.
    Thanks.
    Edited by: Pyrocks on Nov 7, 2010 10:45 AM

    This works on Oracle 11g (probably on 10g too, but I haven't tested):
    CREATE OR REPLACE PACKAGE REUSABLE_RANDOM_NUMBERS
    IS
      FUNCTION GET_NUMBER RETURN NUMBER;
    END REUSABLE_RANDOM_NUMBERS;
    create or replace
    PACKAGE BODY REUSABLE_RANDOM_NUMBERS
    IS
      TYPE NUM_TABLE_TYPE IS TABLE OF CHAR INDEX BY PLS_INTEGER;
      MIN_VALUE CONSTANT PLS_INTEGER := 0;
      max_value CONSTANT PLS_INTEGER := 10;
      NUM_TABLE NUM_TABLE_TYPE;
      FUNCTION GET_NUMBER RETURN NUMBER
      IS
        num PLS_INTEGER;
      BEGIN
        FOR I IN 1 .. 100 LOOP
           NUM := DBMS_RANDOM.VALUE( min_value, max_value );
           IF NOT NUM_TABLE.EXISTS( NUM ) THEN
              NUM_TABLE( NUM ) := 'X';
              RETURN NUM;
           END IF;
        END LOOP;
        FOR I IN MIN_VALUE .. MAX_VALUE LOOP
          IF NOT NUM_TABLE.EXISTS( i ) THEN
              NUM_TABLE( i ) := 'X';
              RETURN i;
           END IF;
        END LOOP;
        RAISE_APPLICATION_ERROR( -20991, 'All possible values have ben used, cannot assign a new one' );
      END;
    END REUSABLE_RANDOM_NUMBERS;
    SELECT REUSABLE_RANDOM_NUMBERS.GET_NUMBER
    FROM DUAL
    connect by level <= 11;
    GET_NUMBER            
    3                     
    4                     
    6                     
    2                     
    1                     
    7                     
    8                     
    0                     
    9                     
    5                     
    10                    
    11 rows selected
    SELECT REUSABLE_RANDOM_NUMBERS.GET_NUMBER
    FROM DUAL;
    Error starting at line 44 in command:
    SELECT REUSABLE_RANDOM_NUMBERS.GET_NUMBER
    FROM DUAL
    Error report:
    SQL Error: ORA-20991: All possible values have ben used, cannot assign a new one
    ORA-06512: przy "TEST.REUSABLE_RANDOM_NUMBERS", linia 26

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

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

Maybe you are looking for