Sample Clause

Hi!
We have a table TCONTENT and a select * view CONTENT on this table.
And we have the following queries:
SQL> select count(*) from tcontent;
COUNT(*)
4639
SQL> select count(*) from content;
COUNT(*)
4639
SQL> select count(*) from tcontent sample(1);
COUNT(*)
56
SQL> select count(*) from content sample(1);
COUNT(*)
4639
Why don't we get the same result at the last two queries?
Can i not specify SAMPLE in a query that selects from a view?
Best regards
Nicole Wonneberger

What db version are you on? Works on 10.2.0.3.0:
michaels>  CREATE OR REPLACE VIEW v_emp
AS
   SELECT *
     FROM emp
View created.
michaels>  SELECT ename
  FROM emp SAMPLE (20)
ENAME    
ALLEN    
JONES    
BLAKE    
ADAMS    
4 rows selected.
michaels>  SELECT ename
  FROM v_emp SAMPLE (20)
ENAME    
ALLEN    
TURNER   
MILLER   
3 rows selected.

Similar Messages

  • Doubt on SAMPLE clause in SELECT statment

    Hi all,
    I am having table with rows of 41. I issued a statement like this
    select * from TABLE_NAME SAMPLE(10);
    and it selected 3 rows (it is varying) . Everytime, i issued this statement, it is
    fetching different number of rows.
    Can anybody please explain what is the basis for it and what is the best
    option to select rows randomly.
    Thanks in advance,
    Pal

    Thanks for your reply.
    Everytime, the selected rows are different sometimes only one record, sometimes
    three, sometimes 7 recoreds, and sometimes 4 records like that.
    So i didnot understand what is going on inside of this query.
    Thanks,
    Pal

  • Order By Clause in View

    Hi,
    I have a doubt regarding Order By Clause in Views.
    As per my knowledge, we can't put an order by clause in the subquery that defines view. But when i created a view in Oracle 9i with the order by clause, view got created.
    Please see the my view code below :
    create or replace view testview
    as select * from employees
    order by 1,2;
    Could anyone please confirm that we can have order by clause in Views in oracle 9i?
    Thanks,
    Tandra

    According to the SQL Reference doc, there is no such restriction for a non-updatable view:
    The view subquery cannot select the CURRVAL or NEXTVAL pseudocolumns.
    If the view subquery selects the ROWID, ROWNUM, or LEVEL pseudocolumns, those columns must have aliases in the view subquery.
    If the view subquery uses an asterisk (*) to select all columns of a table, and you later add new columns to the table, the view will not contain those columns until you re-create the view by issuing a CREATE OR REPLACE VIEW statement.
    For object views, the number of elements in the view subquery select list must be the same as the number of top-level attributes for the object type. The datatype of each of the selecting elements must be the same as the corresponding top-level attribute.
    You cannot specify the SAMPLE clause.
    This restriction exists only for updatable views:
    If you want the view to be inherently updatable, it must not contain any of the following constructs:
    A set operator
    A DISTINCT operator
    An aggregate or analytic function
    A GROUP BY, ORDER BY, CONNECT BY, or START WITH clause
    A collection expression in a SELECT list
    A subquery in a SELECT list
    Joins (with some exceptions as described in the paragraphs that follow).

  • Help in finding Partition_name, no. of rows in each partition

    hello all,
    Please help me in finding out
    Partition_name, no. of rows in each partition, max_value in each partition.
    for a paritioned table
    Please help on this.
    Edited by: user577981 on Jan 2, 2009 9:13 PM

    user577981 wrote:
    I can't analyze that table using dbms_packages as table is having too muchh data in TB.
    Kindly suggest something else in form of sql.That's not really a reason not to use DBMS_STATS. If you're just interested in rough figures, You can use a suitable low "estimate_percent" setting, e.g. you can go as low as 0.000001 percent. You can omit column statistics using an appropriate method_opt option. Something like the following should generate minimum statistics:
    exec dbms_stats.gather_table_stats(
    <owner>,
    <table>,
    estimate_percent=>0.000001,
    method_opt=>'FOR COLUMNS',
    block_sample=>true,
    granularity=>'PARTITION'
    select count(*) c from T partition (...)It might be worth to mention that if you don't have suitable index for performing the count this might take very long, too, so you could revert to the same approach than the "estimate_percent" of DBMS_STATS: You could use the SAMPLE clause to restrict the rows/blocks to sample, e.g.
    select count(*) / 0.000001 c  from T partition (...) sample (0.000001) blocksYou need to scale the count by the same factor as the sample factor.
    Regards,
    Randolf
    Oracle related stuff blog:
    http://oracle-randolf.blogspot.com/
    SQLTools++ for Oracle (Open source Oracle GUI for Windows):
    http://www.sqltools-plusplus.org:7676/
    http://sourceforge.net/projects/sqlt-pp/

  • Select a set of random rows

    I don't understand how the sample clause works on the select statement. Eg. SELECT * FROM clients SAMPLE(50) should return half of all rows in the table, but it's unstable. Sometimes it returns 4, sometimes 3 and even 2 (SELECT COUNT(*) FROM clients returns 6). Why???
    So, if it's really unstable, how do I select a random number of rows from a query? Is there other way?

    As noted, the number of rows returned by SAMPLE can vary. The approach I use is to set the sample number high enough so that the minimum number of rows it returns is always higher than what you want, and then chop off the excess with a rownum filter:
    sql>select empno, ename, job
      2    from emp sample (50)
      3   where rownum <= 3;
        EMPNO ENAME      JOB
         7499 ALLEN      SALESMAN
         7654 MARTIN     SALESMAN
         7839 KING       PRESIDENT
    3 rows selected.
    sql>/
        EMPNO ENAME      JOB
         7566 JONES      MANAGER
         7698 BLAKE      MANAGER
         7782 CLARK      MANAGER
    3 rows selected.
    sql>/
        EMPNO ENAME      JOB
         7499 ALLEN      SALESMAN
         7566 JONES      MANAGER
         7782 CLARK      MANAGER
    3 rows selected.
    sql>/
        EMPNO ENAME      JOB
         7369 SMITH      CLERK
         7521 WARD       SALESMAN
         7839 KING       PRESIDENT
    3 rows selected.

  • Creating a view with order by condition

    Hi all.
    I'm on db 11g.
    I have a doubt: is it possible to create a view using both group by and order by conditions?
    It is like this:
    create or replace view some_view
    as select col1,col2,col3, sum(col4),sum(col5)
    from table_name
    where.....
    group by col1, col2, col3
    order by col1, col2;The problem is that if I put order by conditions it gives me error; if I write those statements without order by condition everything is ok.
    Someone can help me?
    Thanks for collaboration,
    Fabrizio

    >
    Restrictions on the Defining Query of a View The view query is subject to the following restrictions:
    * The subquery cannot select the CURRVAL or NEXTVAL pseudocolumns.
    * If the subquery selects the ROWID, ROWNUM, or LEVEL pseudocolumns, then those columns must have aliases in the view subquery.
    * If the subquery uses an asterisk (*) to select all columns of a table, and you later add new columns to the table, then the view will not contain those columns until you re-create the view by issuing a CREATE OR REPLACE VIEW statement.
    * For object views, the number of elements in the subquery select list must be the same as the number of top-level attributes for the object type. The datatype of each of the selecting elements must be the same as the corresponding top-level attribute.
    * You cannot specify the SAMPLE clause.
    * You cannot specify the ORDER BY clause in the subquery if you also specify the subquery_restriction_clause.
    >
    http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_8004.htm#SQLRF01504

  • Full Table Scans / Index Scans /Index Organized Tables...

    Can anyone give me an example where an index would be the best option to query 99% of data.
    Can anyone give me an example where a FTS is the best option to query 1% of data.
    If IOT are better in terms of performance and also in terms of saving storage space then why cant we always use IOT in the database . Why do we need to follow the regular table and index to store data.
    Responses are appreciated !
    null
    null

    It's easiest to consider extreme cases for thought experiments:
    Can anyone give me an example where an index would
    be the best option to query 99% of data.
    The obvious case would be where you had an order by clause with a matching index. With a well-clustered table, the optimizer might decide to do an index full scan to collect 100% of the data in order rather then doing a tablescan and sort.
    In fact, with first_rows_1 optimization, and certainly with first_rows optimization before it, you would sometimes see the optimizer use such a strategy to read 100% of the data in the right order, discarding 99% of it, rather than selecting 1% of the data through a more precise index and sorting it.
    Can anyone give me an example where a FTS is the
    best option to query 1% of data.
    Consider a table in a tablespace with an 8Kb block size - with short rows (roughly 80 bytes) you can get 100 rows per block. Run a query that wants to get one row from each block (i.e. 1% of the data). A tablescan with a db_file_multiblock_read_count of just 2 would be more efficient than an indexed access. For a more realistic example consider picking one row from every 16th block when your db_file_multiblock_read_count is 128.
    In fact, if you check what Oracle does when you sample 1% of the rows using the sample clause, you may see cases where it actualy uses multiblock reads to scan the whole table, discarding the blocks it doesn't want.
    Regards
    Jonathan Lewis
    http://jonathanlewis.wordpress.com
    http://www.jlcomp.demon.co.uk

  • SQL 문장이 RULE 에서 COST-BASED로 전환되는 경우

    제품 : ORACLE SERVER
    작성날짜 : 2004-05-28
    SQL 문장이 RULE에서 COST-BASED로 전환되는 경우
    ==============================================
    PURPOSE
    SQL statement 문장이 자동으로 cost-based mode로 전환되는 경우에 대해
    알아보자.
    Explanation
    Rule-based mode에서 sql statement를 실행하더라도 Optimizer에 의해
    cost-based mode로 전환되는 경우가 있다.
    이런 경우는 해당 SQL이 아래와 같은 경우로 사용되는 경우 가능하다.
    - Partitioned tables
    - Index-organized tables
    - Reverse key indexes
    - Function-based indexes
    - SAMPLE clauses in a SELECT statement
    - Parallel execution and parallel DML
    - Star transformations
    - Star joins
    - Extensible optimizer
    - Query rewrite (materialized views)
    - Progress meter
    - Hash joins
    - Bitmap indexes
    - Partition views (release 7.3)
    - Hint (RULE 또는 DRIVING_SITE제외한 Hint가 왔을경우)
    - FIRST_ROWS,ALL_ROWS Optimizer의 경우는 통계정보가 없어도 CBO로 동작
    - TABLE 또는 INDEX에 Parallel degree가 설정되어 있거나,
    INSTANCE가 설정되어 있는 경우(DEFAULT도 해당)
    - Table에 domain index(Text index등) 이 생성되어 있는 경우

  • Update query issue to update middle (n records) of the rows in a table

    Hi
    I have a below requirement for that I gone thru one below appoch to fulfill my requirement.
    Requirement:
    I need to pull 3 crore data thru ODI, source table does not have a primary key and it have 200 columns with 3 crores records (it has a 25 columns as composite key).
    I need to populate those 3 crores records into target oracle DB but when I tried to load 3 crores at time I got an error so I approch incremental load, since for that I need to update for each 1 crore records with flg1,flg2 anf flg3 (flag values), for this update I have added one more column in source table using those flag values I can populate 1 crore records in target machine.
    Approch
    For aove requirement I writem below query to update flg1 for first crores records update tbl_name set rownum_id='flg1' where rownum<=10000000; and it updated successfully without any error, for second, to update flg2 for 2nd crore records I wrote below update query and it execute 20min and given *0 rows updated* Please help if below query is wrong
    Query: update tbl_name set rownum_id='flg2' where rownum<=20000000 and rownum_id is NULL;
    Thanks in advance
    Regards,
    Phanikanth

    A couple of thoughts.
    1. This forum is in English and accessed by people in more than 100 countries. Use metric counts not crore. Translate to million, billions, trillions, etc.
    2. No database version ... makes helping you very hard.
    3. 200 columns with 25 in a composite key is a nightmare by almost any definition ... fix your design before going any further.
    4. What error message? Post the complete message not just your impression of it.
    5. Oracle tables are heap tables .. there is no such concept as the top, the bottom, or the middle.
    6. If you are trying to perform sampling ... use the SAMPLE clause (http://www.morganslibrary.org/reference/select.html#sssc).
    7. What is ODI? Do not expect your international audience to know what the acronym means.

  • Random number generation that sticks

    Hello,
    I would appreciate any help with the appropriate JavaScript to generate a random 8 digit number XXXX-XXXX on a form when the user starts to enter data. This number would need to be permanent so that it can be used as a tracking identifier later.
    Thanks for looking.
    Dawson

    If you're using Oracle8i, you can use the new SAMPLE clause in the FROM clause of the SELECT statement to query a random sample from a single table. Otherwise, just write a simple random number generator in PL/SQL (see any good algorithm book under the topic "Psuedorandom number generator"). You need to understand a bit about statistics, if being "truly" random is important, to use these tools.

  • Random result set from cursor

    Hello all,
    I have a cursor defined that simply performs a SELECT. I would like to be able to dynamically state whether I'd like the entire result set returned or a random selection.
    The issue I'm having is that because the cursor is already defined I am trying to build this functionality into the LOOP. I am able to return random sets by using DBMS_RANDOM but I've only been able to do this when modifying the SELECT statement. I have considered an ORDER BY in the cursor and then simply EXIT'ing when the ROWNUM meets a certain number of returned results. This would, at least, provide the ability to return a user specified number of random records. Perhaps the ORDER BY could be modified by a cursor parameter?
    I'm hoping there's an elegant solution that I'm missing.
    Thanks for any help!
    Mark

    user10368702 wrote:
    Thanks for pointing out this feature to me. The problem is that my cursors are currently doing multi-table joins and the SAMPLE clause will not work with them. To clarify, I would like to programatically decide whether I'd like to return all the rows from the cursor, or just a sampling. The current method being used it to generate a random number and loop through the entire cursor until that rownum is found. I dislike the table walk, but am unable to come up with a way to return a specific sample size or record num. Ideally I'd like to be able to perform the equivalent of ROWNUM = X with the results from the cursor.
    Thanks for any help!Probably you can't use dynamic SQL (using OPEN or EXECUTE IMMEDIATE) for a particular reason? Because in that case you could just use your query as an inline view like that:
    SELECT * FROM (
    <YOUR_QUERY_INCLUDING DBMS_RANDOM_VALUE>
    WHERE <RANDOM_VALUE> <= <YOUR_LIMIT>and construct your query dynamically.
    Regards,
    Randolf
    Oracle related stuff blog:
    http://oracle-randolf.blogspot.com/
    SQLTools++ for Oracle (Open source Oracle GUI for Windows):
    http://www.sqltools-plusplus.org:7676/
    http://sourceforge.net/projects/sqlt-pp/
    Edited by: Randolf Geist on Sep 29, 2008 11:21 PM
    Removed unnecessary ORDER BY

  • Help in finding lens profile

    I looked in adobe lens profile creator and was unable and could not find a profile for Nikon D90 camera and Nikkor 300mm prime lens !
    Where else to look and find what I'm looking 4 ?

    user577981 wrote:
    I can't analyze that table using dbms_packages as table is having too muchh data in TB.
    Kindly suggest something else in form of sql.That's not really a reason not to use DBMS_STATS. If you're just interested in rough figures, You can use a suitable low "estimate_percent" setting, e.g. you can go as low as 0.000001 percent. You can omit column statistics using an appropriate method_opt option. Something like the following should generate minimum statistics:
    exec dbms_stats.gather_table_stats(
    <owner>,
    <table>,
    estimate_percent=>0.000001,
    method_opt=>'FOR COLUMNS',
    block_sample=>true,
    granularity=>'PARTITION'
    select count(*) c from T partition (...)It might be worth to mention that if you don't have suitable index for performing the count this might take very long, too, so you could revert to the same approach than the "estimate_percent" of DBMS_STATS: You could use the SAMPLE clause to restrict the rows/blocks to sample, e.g.
    select count(*) / 0.000001 c  from T partition (...) sample (0.000001) blocksYou need to scale the count by the same factor as the sample factor.
    Regards,
    Randolf
    Oracle related stuff blog:
    http://oracle-randolf.blogspot.com/
    SQLTools++ for Oracle (Open source Oracle GUI for Windows):
    http://www.sqltools-plusplus.org:7676/
    http://sourceforge.net/projects/sqlt-pp/

  • MBO update query issue

    Dear All
    when i create MBO and try to execute the update query it give me a success but it is not reflect the Database.
    update Timesheet set StatusName='from SAP1231231' where TimesheetId=118729.
    Regard
    Ali

    A couple of thoughts.
    1. This forum is in English and accessed by people in more than 100 countries. Use metric counts not crore. Translate to million, billions, trillions, etc.
    2. No database version ... makes helping you very hard.
    3. 200 columns with 25 in a composite key is a nightmare by almost any definition ... fix your design before going any further.
    4. What error message? Post the complete message not just your impression of it.
    5. Oracle tables are heap tables .. there is no such concept as the top, the bottom, or the middle.
    6. If you are trying to perform sampling ... use the SAMPLE clause (http://www.morganslibrary.org/reference/select.html#sssc).
    7. What is ODI? Do not expect your international audience to know what the acronym means.

  • Newbie Q: Limiting the result count

    Hi,
    I wanted to know if there is any other way to limit the result set other than using this:
    SELECT * FROM (select display_url, rownum as r from table_name) where r <= 10;
    Its a times like these that mysql looks so easy to use with its LIMIT feature.
    thanks

    Hi,
    SELECT  display_url
    FROM    table_name
    SAMPLE    (5);will returns about 5% of the rows you would get without the SAMPLE clause. Don't expect exactly 5%.
    Unlike the ROWNUM technique, this will produce a random sampling.
    For details, see the [SQL Language Reference man ual|http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/statements_10002.htm#sthref9780].

  • Simple Order of Magnitude counts.. do they exist ?

    I don't normally deal with SQL, so apologies if what I am asking is dumb / obvious.
    I have a table [orders] with approx 300,000,000 rows. It is quite wide (approx 500b on avg).
    there is a unique index [idx_a] on [order_id , order_dt, store_chain, store_id]
    there is another index [idx_b] on [order_dt, ...several other columns...]
    At a high level I want to do something like:
    SELECT TO_CHAR(order_dt, 'YYYY'), COUNT(*)
    FROM orders
    GROUP BY order_dt
    But I am not really interested in the exact count, I am more interested in an order of magnitude summary. The system is online and live and continually accepting orders from the various outlets (approx 20 per minute). I have tried running the above query, in a test environment but it does not complete inside of 15 minutes.
    Is there a smarter way to do this ?

    Howler_Fish wrote:
    At a high level I want to do something like:
    SELECT TO_CHAR(order_dt, 'YYYY'), COUNT(*)
    FROM orders
    GROUP BY order_dt
    But I am not really interested in the exact count, I am more interested in an order of magnitude summary. The system is online and live and continually accepting orders from the various outlets (approx 20 per minute). I have tried running the above query, in a test environment but it does not complete inside of 15 minutes.
    Is there a smarter way to do this ?Apart from the other advices you've already got, you could try to use "sampling" if you're actually interesting in just a "rough" estimate:
    SELECT TO_CHAR(order_dt, 'YYYY'), COUNT(*) * 10 as cnt
    FROM orders sample (10)
    GROUP BY order_dt;
    This would "sample" only 10% of the rows using the "SAMPLE" clause, therefore you would have to multiply the count by the same factor to get results comparable to the "actual" query.
    Please note that depending on how "skewed" the distribution of your data is across the table blocks if you use only a low sample size your results might be way off, so you might need to test with a different degree of sampling.
    Regards,
    Randolf
    Oracle related stuff blog:
    http://oracle-randolf.blogspot.com/
    SQLTools++ for Oracle (Open source Oracle GUI for Windows):
    http://www.sqltools-plusplus.org:7676/
    http://sourceforge.net/projects/sqlt-pp/

Maybe you are looking for

  • Query performance tuning

    Hello, Can someone please tell me if there is anyway to improve this query to perform better.I tried using temp table instead of CTE .it did'nt change anything.I think there is a problem with latter part of query.When I execute every select individua

  • PBO and PA! to Dynpro SAPMV45A 8459 do not execute

    Hi all, I found several threads about Dynpro 8459, which contains "Additional Data B" in the sales order. But I have a problem which isn't mentioned earlier. My problem ist that I did some coding in the PBO of dynpro 8459, but it isn't executed. When

  • How to create confirmation pop in process classes

    Hello experts,          I have a requirement to create a Confirmation pop up in a Zprocess -> Z process class-> method. This method is triggering when user selects contract line item and press on change contract button than selects any one process fr

  • SAP Rules / Considerations behind ATP for Purchase Orders

    Hi Can anyone guide me to the considerations taken into account for ATP check for Purchase orders, Kind Regards Bhavana

  • Save partially complete form to be completed online later

    Hi All I am still new and have not touch this Reader extensions. I am trying to find a solution for a customer who wants to deploy forms to a server and allow their client to fill in and save back to the server. The challenge is that the form will be