Selecting random records out of a table

Hi,
I guess this question isn't new, but I didn't found anything about this using the search of this forum.
How can I get e.g. 5 random records out of a table?
I have a small table, which stores the special offers of a shop. Let us say, there are 30 records in it. How can I fetch (e.g.) 5 random records of this table?
I tried to use this statement in a loop:
SELECT t_item_id FROM tbl_special_offers SAMPLE (1) WHERE ROWNUM = 1
But this is a very small table, so most of the query returns no data. Additionally I have to check if this number was already selected and ignore it in this case. This isn't a good solution, is it?
Can somebody help me out with a better solution? Thanks :)

create or replace package shop_stuff
is
   function random_number return number;
end;
create or replace package body shop_stuff
is
   function random_number return number
   is
   begin
      return dbms_random.value;
   end;
begin
   dbms_random.initialize (to_number(to_char(sysdate,'mmddsssss')));
end;
create table tbl_special_offers (t_item_id number);
insert into tbl_special_offers values (1);
insert into tbl_special_offers values (2);
insert into tbl_special_offers values (3);
insert into tbl_special_offers values (4);
insert into tbl_special_offers values (5);
insert into tbl_special_offers values (6);
insert into tbl_special_offers values (7);
insert into tbl_special_offers values (8);
insert into tbl_special_offers values (9);
insert into tbl_special_offers values (10);
select t_item_id
  from (select t_item_id
          from tbl_special_offers
         order by shop_stuff.random_number)
where rownum <= 5                       
SQL> /
T_ITEM_ID
         6
         7
         5
         4
        10
SQL> /
T_ITEM_ID
         1
         5
         3
         9
         6
SQL> /
T_ITEM_ID
         6
         5
         3
         2
        10
SQL> /
T_ITEM_ID
        10
         2
         8
         4
         1
SQL>

Similar Messages

  • Select Random Records with Group By?

    Hi,
    I currently select random records by using this type of SQL:
    (SELECT *
    FROM ( SELECT *
    FROM ( SELECT *
    FROM TABLEA
    ORDER BY dbms_random.value
    WHERE ROWNUM <= 100
    Based on the following data, I now want to still pick out random records but I only want 1 record from the same ID and START_DATE but where the FLAG could be Y or N.
    So with grouping by ID and START_DATE, I need to still be able to choose the record if it has anything from 1 entry or 10 entries per ID and START_DATE.
    Could this be performed with a GROUP BY?
    ID START_DATE FLAG
    1 12/12/2005 Y
    1 12/12/2005 N
    1 12/12/2005 N
    1 30/12/2005 Y
    1 30/12/2005 N
    1 30/12/2005 N
    2 10/10/2005 Y
    2 07/07/2005 Y
    Thanks for any help.
    Daniel

    Try this [not tested]:
    SELECT *
         FROM
              (SELECT *
                   FROM
                   ( SELECT
                              ID
                             ,START_DATE
                             ,FLAG
                             ,ROW_NUMBER() OVER
                                  (PARTITION BY ID,START_DATE ORDER BY dbms_random.value) RN
                        FROM TABLEA
                   ORDER BY dbms_random.value
         WHERE RN = 1
              AND ROWNUM <= 100
         ;

  • Selecting specific records out of the same table with PICS

    Post Author: nambi
    CA Forum: Formula
    I have a Database table in which we have information for our paint codes,
    This database when accessed through our will display the types of tests we do for the products we manufacture, we manually enter in these results through the software.  When I open up this same table in access I noticed that each test we do is displayed as new entry under the same product, therefore I have several entries for the same product code, and since we have several tests for each I am unable to specifically pull out the data I need.
    For example I need to create a data sheet for our customers displaying the bake time for these all our products the Product code (formkey) is listed multiple times but all I need is to record the Bake (TargetAlphaValue) time. Out of this table I will also need to report on the Gloss. If I use the record selection I am only able to display one type of test although I will need to specify other types as well.  This is the area I have the problem with,
    I have shown in a jpg what I am looking for, would anyone here know how to pull out only the TargetAlphaValue and associate it to the bake and formkey?  Then do the same with the Gloss test and pull up the TargetAlphaValue for that it would be of great help

    Can you be more precise , please :
    - which table stores the people identities ? (I call this one Identity)
    - which table gives the class where the student works in (I cal l this one Claa_attendees)
    - which table gives the instructor of a class (I call this one Class)
    If your issue is that you have one table which stores Itendities , and you need to display Student identity and Instructor Identity, you have to call this table twice in your query , using table aliases . I mean :
    Select Stud_iden.name, Instr_iden.name
    From Identity Stud_iden, Identity Instr_iden, Class_attendees, Class
    Where Class.clas_id = class_attendees.class_id
    and class.instructor_id = Instr_iden.people_id
    and class_attendees.student_id = Stud_iden.people_id
    Is this what you need to do ?

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

  • How can I select random records from one column

    How can I random select 400 records from a column contains more than 500,000 records? And how long will it take in oracle? Thanks.

    here is one option: (just change 5 to suit your needs...)
    SQL>select * from (
      2  select object_name
      3  from all_objects
      4  order by dbms_random.random
      5  ) where rownum < 5
      6  /
    OBJECT_NAME
    UTL_SYS_COMPRESS
    GV_$LOG_HISTORY
    GV_$LOGMNR_LOGS
    WWV_FLOW_THEME_7
    SQL>/
    OBJECT_NAME
    WWV_FLOW_UPGRADE_REPORT
    WRI$_ADV_SQLT_STATISTICS_PK
    V_$DATABASE
    GV_$SERVICEMETRIC
    SQL>/
    OBJECT_NAME
    WWV_FLOW_CREATE_FLOW_API
    WRH$_SERVICE_WAIT_CLASS_BL
    EXU8SNAPL
    GV$SERVICEMETRIC_HISTORY
    SQL>                well, regarding how long will it take... it depends from lots of variables...
    Cheers,
    Andrea

  • Need help on selection of records in dynamically created table

    hi,
    Ia m able to bind the onleadSelect event to the dynamially created table .
    But i was not able to select the table records.
    default first record was only selected.
    can u help me out to find the way.
    i am pasting the code for reference.
    can u suggest me the right direction.
    i want the selected record in the table to be dispalyed in another view thru this action event.
    but only the forst record is now getting selected by default.
    here the code.
    IWDNode node =wdContext.currentContextElement().node().getChildNode(nodename,0);
    for (int l = 0; l < node.size(); l++) {
    int ele = node.getLeadSelection();
    IWDNodeElement element= node.getElementAt(ele);
    table.setOnLeadSelect(wdThis.wdGetObjectSelectedAction());

    Hi,
      <a href="/people/sap.user72/blog/2005/05/09/have-you-played-blindfold-chess's</a> how to create a dynamic table, though I think you have already done this.
      Do look at the comment that Armin Reichert has put in. Now in the source code that he has provided, the last line should be
    table.setOnLeadSelect(wdThis.wdGetLeadSelectAction());
    Have you done something similar to this?
    Have you set the initializeLeadSelect property of the datasource node to true?
    Regards,
    Satyajit.
    Message was edited by: Satyajit Chakraborty

  • Dynamic Table with Random Records

    What I am trying to do is select random records from a table
    and display them in a dynamic table with max columns set to 3 and
    the 4th record to be on a new row. Below is what I have right now
    and it works to randomly pick records but has no function to set
    columns in a table. If there is an easier way feel free to let me
    know. I have tried various ways to do this but none seem to work.
    <CFQUERY NAME="getItems" DATASOURCE="absi">
    SELECT catfit.*, modcats.*, prodmat.*, prod.* FROM catfit,
    modcats,
    prodmat, prod WHERE prodmat.prodid=catfit.prodid And
    catfit.catid=modcats.catid
    ORDER BY modl ASC </cfquery>
    <cfif getItems.recordCount>
    <cfset showNum = 3>
    <cfif showNum gt getItems.recordCount>
    <cfset showNum = getItems.recordCount>
    </cfif>
    <cfset itemList = "">
    <cfloop from="1" to="#getItems.recordCount#"
    index="i">
    <cfset itemList = ListAppend(itemList, i)>
    </cfloop>
    <cfset randomItems = "">
    <cfset itemCount = ListLen(itemList)>
    <cfloop from="1" to="#itemCount#" index="i">
    <cfset random = ListGetAt(itemList, RandRange(1,
    itemCount))>
    <cfset randomItems = ListAppend(randomItems, random)>
    <cfset itemList = ListDeleteAt(itemList,
    ListFind(itemList, random))>
    <cfset itemCount = ListLen(itemList)>
    </cfloop>
    <cfloop from="1" to="#showNum#" index="i">
    <cfoutput>
    <table width="205" border="0" align="left"
    cellpadding="0" cellspacing="0">
    <tr>
    <td width="235" height="116"> <div
    align="center"><img
    src="../Products/ProductPictures/#getitems.pic[ListGetAt(randomItems,
    i)]#" width="100"></div></td>
    </tr>
    <tr>
    <td
    class="ProdTitle">#getitems.brand[ListGetAt(randomItems,
    i)]# #getitems.modl[ListGetAt(randomItems, i)]#</td>
    </tr>
    <tr>
    <td
    class="paragraph">$#getitems.prc[ListGetAt(randomItems,
    i)]#</td>
    </tr>
    <tr>
    <td><A
    href="../Products/details.cfm?prodid=#getItems.prodid[ListGetAt(randomItems,
    i)]#" class="linkcontact">more
    info</a></td>
    </tr>
    <tr>
    <td> </td>
    </tr>
    </table>
    </cfoutput>
    </cfloop>
    </cfif>

    To start a new row after 3 records, do something like this.
    <table>
    <tr>
    <cfoutput query="something">
    <td>#data#<td>
    <cfif currentrow mod 3 is 0>
    </tr><tr>
    </cfoutput>
    </tr>
    </table>
    You should also know that your approach is very inefficient
    in that you are bringing in to cold fusion more data than you need.
    First of all you are selecting every field from 3 tables when you
    don't appear to be using all of them. Second, you are selecting
    every record and you only want to use 3. There are better ways out
    there, but they are db specific and you did not say what you are
    using.

  • Selecting Randoms from Query of Queries

    I can create a query that selects random records
    <cfquery....>
    select top 10 * from table order by newid() <!--- SQL
    Server --->
    </cfquery>
    or
    <cfquery....>
    select top 10 * from table order by rand() limit 10 <!---
    MySQL--->
    </cfquery>
    However, is there a way to cache a query then select random
    records from it?
    I want to cache the overall query that retrieves all the
    records, then
    randomly pull
    from that cached query.
    If I use newid() or rand(), the query bombs on the
    parentheses.
    Any suggestions?
    Tami

    well, it's not really a query of queries... more like a query
    of a cached
    query :)
    "DixieGal" <[email protected]> wrote
    in message
    news:ffsn1b$***$[email protected]..
    |I can create a query that selects random records
    | <cfquery....>
    | select top 10 * from table order by newid() <!--- SQL
    Server --->
    | </cfquery>
    |
    | or
    | <cfquery....>
    | select top 10 * from table order by rand() limit 10
    <!--- MySQL--->
    | </cfquery>
    |
    | However, is there a way to cache a query then select random
    records from
    it?
    | I want to cache the overall query that retrieves all the
    records, then
    | randomly pull
    | from that cached query.
    |
    | If I use newid() or rand(), the query bombs on the
    parentheses.
    |
    | Any suggestions?
    |
    | --
    |
    | Tami
    |
    |

  • Selecting records from DB table with out using internal tables

    hi,
    i need to retrieve values from a database table based on few fields and date as well. however, i need to check whether the date is less or equal to the current date and along with that i should get the appropriate record. how can i do that with out using internal table.
    field1-----date---
    11111----
    20070219
    11111--20070214 <---
    11111----
    20070205
    in the above scenario i should get the second record
    Regards,
    Kranthi.

    Try:
    REPORT ztest MESSAGE-ID 00.
    TABLES bkpf.
    SELECT * FROM bkpf
      UP TO 1 ROWS
      WHERE budat <= sy-datum
      ORDER BY budat DESCENDING.
    ENDSELECT.
    Rob

  • Selecting Non repeatable random records

    HI all,
     I have 20 records in table. I want to get a random single  record from that table.And the main thing is
    if i having 20 records 1st time i'm getting a random record.the upcoming execution result that does not show previous random record .
    That is out of 20 records ,each time i want to select record that does not occur previously.so at 20 executions i have 20 result with non-repeatable.
    If i am confusing you,sorry for this.....pls help me to get a suffled record at each time
    note: i'm used NEWID() that gives random records but it occurs previously some time

    I cannot reproduce this :-)
    with
    [10] as (select 0 as c union all select 0),
    [11] as (select 0 as c from [10] as a, [10] as b),
    [12] as (select 0 as c from [11] as a, [11] as b),
    [13] as (select 0 as c from [12] as a, [12] as b),
    nums as (select top(20) row_number() over(order by c) as n from [13]),
    choice as (select top(1) n from nums order by checksum(newid()))
    select * from choice order by n 
    Best Regards,Uri Dimant SQL Server MVP,
    http://sqlblog.com/blogs/uri_dimant/
    MS SQL optimization: MS SQL Development and Optimization
    MS SQL Consulting:
    Large scale of database and data cleansing
    Remote DBA Services:
    Improves MS SQL Database Performance
    SQL Server Integration Services:
    Business Intelligence

  • How can I select the random records in u201Cstep loopu201D.

    Hi, Experts,
    I am using step loop to display the data on screen now I want to select the random records from this step loop display. Like 1st 3rd or 5th record, is there any way to select the records,
    like I did in Table control there was a filed in internal table named marked char length 1, I gave this field name in u201Cw/ SelColumnu201D it fill that field with u2018Xu2019 from where I can get the info about the selected records, in this way I can easily perform the operation on that internal table with the help of that marked field.
    Is there any way to select the records in step loop too ?
    Kind Regards,
    Faisal

    thanks for replay shwetali,
    but i just gave you example of random records with 1st 3rd and 5th my goal is not select only these records. i want to select the random mean any records from the step loop display.
    like we can select from the table control. and when select any record it place 'X' in the given internal table field.
    Thanks and kind Regards,
    Faisal

  • Help with selecting 10 random records from all records meeting report selection criteria in Crystal 11

    <p>I am trying to select ten random records from all that match the report selection criteria then report on each of these random records for QA/QI.  I have tried the RND function however it is giving me a random number rather than a random record selection.  I cannot figure this out and am despirately seeking assistance.</p><p>Thank you,</p><p>Amy</p>

    <p>I don&#39;t know of any Random record selection functions but maybe you could write your own custom function inside of a record selection to randomly filter the records.  You would use the Rand function we currently have to decide if a record was included in the report data or not.</p><p>Another possible option is to filter the records before they get to the report.  You can only do this if you are pushing the data into the report instead of having the report pull the data.  An example of this would be passing an ado recordset to a report at runtime. </p><p>Rob Horne</p><p>http://diamond.businessobjects.com/blog/10 </p>

  • How to select multiple records from a TREE in the table

    HI,
    I have a tree structure which is in the table.When I open the node of the tree,all the subnodes are coming as one-one records in the table.I want to slect multiple record from this table.I applied onLeadSelect for this table,I can select only 1 record from the table.
    Can any one plz suggest me how to select multiple records from the table so that I can get all the data of those selected record.
    Regards
    -Sandip

    Rashmi/Kukku,
    First of all, Thanks for your help!
    Is there any other way in which we can access tables other than using BAPIs or RFCs?
    In my case, there is a table structure which has to be updated with values after validating a key. i don't think there is any RFC available now. do i need to create bapi/rfc for that?
    Krishna Murthy

  • How to get number of records in all user tables in one select

    Please advise how to retrieve the number of records in all user tables in one select. I would likt to extract the data to excel file.
    Many thanks,
    Andrew

    You could always analyze the tables:
    declare
    begin
      for X in (select owner, table_name from all_tables
                 minus
                select owner, table_name from all_external_tables) LOOP
          dbms_stats.Gather_Table_Stats(X.Owner, X.Table_Name) ;
      end loop;
    end;
    /Then: Select Owner, Table_Name, Num_Rows from All_Tables ;

  • How to select multiple records in ALV with out pressing ctrl

    Hi Experts,
    Is there a way to select multiple records in ALV with out pressing ctrl button on the key board?
    Selection and deselection should allow multiple records.
    any clue is highly appreciated.
    regards,
    Ajay

    The keyboard always plays a role, although with the Shift key you can select blocks of records.
    ○       CTRLclick, CTRLspacebar
    Toggles a selection.
    ○       SHIFTclick, CTRLshift
    Selects the area from the lead selection to the row selected. If no lead selection is set, the selection starts from the first row. In the multiNoLead mode, the selection starts from the row last selected

Maybe you are looking for