Intersect vs In clause in subquery

Hi,
Can anyone explain why "intersect" seems to be faster compare to using "columnA in" clause when dealing with subquery?
Is intersect from common SQL standard?
Is there any website that shows SQL standard that we use today?
Please advise.
thanks.

I always like to read these explanations:
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:442029737684
which points to: http://asktom.oracle.com/pls/asktom/f?p=100:11:1843855892052020::::P11_QUESTION_ID:953229842074

Similar Messages

  • DECODE is not working in WHERE clause when subquery returns more rows

    Hi Gurus,
    I want to write a query on CCENTERS table(Script given below) and expect the following result:
    1. When I pass a value of 0 for ID, It returns all the rows given in the table.
    2. When I pass a value other than 0, It returns the row for the given value as well as all its child records.
    CCENTER has parent-child relationship in ID and BASE column. I am using a query with DECODE function. but DECODE function in WHERE clause is not capable of handling sub-query with multiple rows.
    VARIABLE ParaCCenter NUMBER
    BEGIN
    :paraccenter:=0;
    END;
    CREATE TABLE ccenters
    (id NUMBER,
    name VARCHAR2(20),
    base number);
    INSERT INTO ccenters VALUES(1,'NUST',null);
    INSERT INTO ccenters VALUES(2,'SEECS',1);
    INSERT INTO ccenters VALUES(3,'NBS',1);
    commit;
    SELECT * FROM ccenters
    WHERE id IN DECODE(:ParaCCenter, 0, id,
    (SELECT id FROM ccenters
    START WITH base=:ParaCCenter
    CONNECT BY PRIOR id = base
    UNION
    SELECT :ParaCCenter FROM dual
    BEGIN
    :paraCCenter:=1;
    END;
    SELECT * FROM ccenters
    WHERE id IN DECODE(:ParaCCenter, 0, id,
    (SELECT id FROM ccenters
    START WITH base=:ParaCCenter
    CONNECT BY PRIOR id = base
    UNION
    SELECT :ParaCCenter FROM dual))
    The result is
    (SELECT id FROM ccenters
    ERROR at line 3:
    ORA-01427: single-row subquery returns more than one row
    How this query can be rewritten for the given functionality. Any response will be highly appreciated.
    Thanks

    And if you want to use DECODE:
    SQL> BEGIN
      2  :paraccenter:=0;
      3  END;
      4  /
    PL/SQL procedure successfully completed.
    SQL> select  *
      2    from  ccenters
      3    where :paraccenter = decode(:paraccenter,0,0,id)
      4  /
            ID NAME                       BASE
             1 NUST
             2 SEECS                         1
             3 NBS                           1
    SQL> BEGIN
      2  :paraccenter:=2;
      3  END;
      4  /
    PL/SQL procedure successfully completed.
    SQL> select  *
      2    from  ccenters
      3    where :paraccenter = decode(:paraccenter,0,0,id)
      4  /
            ID NAME                       BASE
             2 SEECS                         1
    SQL> SY.

  • Where clause of SubQuery

    Hello!I beg your pardon for my poor English.
    Oracle prompts "invalid month" when running the following sentence:
    select *
    from xtcs xtcs
    where xtcs.csmc like '%month'
    and (xtcs.cnq,xtcs.csmc) not in (
    select distinct
    to_char(add_months(to_date((case when substr(yhjf1.pzh,1,2)>='50' then '19' else '20' end)||substr(yhjf1.pzh,1,4),'yyyymm'),-4),'yyyy') pzcnq
    ,yhjf1.pzhbs||'month'
    from yhjf yhjf1
    where yhjf1.pzhbs is not null);
    But,oracle runs well when running only the subquery in where clause:
    select distinct
    to_char(add_months(to_date((case when substr(yhjf1.pzh,1,2)>='50' then '19' else '20' end)||substr(yhjf1.pzh,1,4),'yyyymm'),-4),'yyyy') pzcnq
    ,yhjf1.pzhbs||'month'
    from yhjf yhjf1
    where yhjf1.pzhbs is not null;
    I have checked the data in the table yhjf.And there are some wrong about field pzh which cause oracle wrong .But the where clause 'yhjf1.pzhbs is not null' can filter them out.I'm being in puzzle now.Please tell me why and how I can do.Thanks very much!

    > Sorry,I'm a Chinese.The names originally were in
    Chinese.I converted them into alphabets before posting.
    I did not think of that option. I'm glad to hear that the names are meaningful to you :-)
    > My data is very large and I had not created a
    small data set on which the error happens.
    To know what the problem is, you will have to identify the rows that are causing the trouble. Once identified, the solution should be simple.
    Regards,
    Rob.

  • Having clause and subquery

    Hi,
    The below result Is retrieved from Table T1(Select * From T1),
    ID CODE
    101 A1
    102 A1
    103 A2
    104 A1
    105 B1
    106 B1
    107 B5
    I want the result like below,
    101 A1
    102 A1
    104 A1
    105 B1
    106 B1
    Can anyone help me to get the expected result.

    Hi Dhiva !
    you can get result with order by clause.
    do you want this?
    WITH
    DATA AS
    (select 101 as id, 'A1' val from dual union all
    select 102 as id, 'A1' val from dual union all
    select 103 as id, 'A2' val from dual union all
    select 104 as id, 'A1' val from dual union all
    select 105 as id, 'B1' val from dual union all
    select 106 as id, 'B1' val from dual union all
    SELECT 107 AS ID, 'B5' VAL FROM DUAL)
    SELECT *  FROM DATA
    ORDER by val, id

  • Execution of subquery of IN and EXISTS clause.

    Hi Friends,
    Suppose we have following two tables:
    emp
    empno number
    ename varchar2(100)
    deptno number
    salary number
    dept
    deptno number
    location varchar2(100)
    deptname varchar2(100)
    status varchar2(100)
    Where dept is the master table for emp.
    Following query is fine to me:
    SELECT empno, ename
    FROM emp,dept
    WHERE emp.deptno = dept.deptno
    AND emp.salary >=5000
    AND dept.status = 'ACTIVE';
    But I want to understand the behaviour of inline query (Used with IN and EXISTS clause) for which I have used this tables as an example (Just as Demo).
    1)
    Suppose we rewrite the above query as following:
    SELECT empno, ename
    FROM emp
    WHERE emp.salary >=5000
    AND deptno in (SELECT deptno FROM dept where status = 'ACTIVE')
    Question: as shown in above query, suppose in our where clause, we have a condition with IN construct whose subquery is independent (it is not using any column of master query's resultset.). Then, will that query be executed only once or will it be executed for N number of times (N= number of records in emp table)
    In other words, how may times the subquery of IN clause as in above query be executed by complier to prepared the subquery's resultset?
    2)
    Suppose the we use the EXISTS clause (or NOT EXISTS clause) with subquery where, the subquery uses the field of master query in its where clause.
    SELECT E.empno, E.ename
    FROM emp E
    WHERE E.salary >=5000
    AND EXISTS (SELECT 'X' FROM dept D where status = 'ACTIVE' AND D.deptno = E.deptno)
    Here also, I got same confusion. For how many times the subquery for EXISTS will be executed by oracle. For one time or for N number of times (I think, it will be N number of times).
    3)
    I know we can't define any fix thumbrule and its highly depends on requirement and other factors, but in general, Suppose our main query is on heavily loaded large transaction table and need to check existance of record in some less loaded and somewhat smaller transaction table, than which way will be better from performance point of view from above three. (1. Use of JOIN, 2. Use of IN, 3. Use of EXISTS)
    Please help me get solutions to these confusions..
    Thanks and Regards,
    Dipali..

    Dipali,
    First, I posted the links with my name only, I don;t know how did you pick another handle for addressing it?Never mind that.
    >
    Now another confusion I got.. I read that even if we used EXISTS and , CBO feels (from statistics and all his analysis) that using IN would be more efficient, than it will rewrite the query. My confusion is that, If CBO is smart enough to rewrite the query in its most efficient form, Is there any scope/need for a Developer/DBA to do SQL/Query tuning? Does this means that now , developer need not to work hard to write query in best menner, instade just what he needs to do is to write the query which resluts the data required by him..? Does this now mean that now no eperts are required for SQL tuning?
    >
    Where did you read that?Its good to see the reference which says this.I haven't come across any such thing where CBO will rewrite the query like this. Have a look at the following query.What we want to do is to get the list of all teh departments which have atleast one employee working in it.So how would be we write this query? Theremay be many ways.One,out of them is to use distinct.Let's see how it works,
    SQL> select * from V$version;
    BANNER
    Oracle Database 11g Enterprise Edition Release 11.1.0.6.0 - Production
    PL/SQL Release 11.1.0.6.0 - Production
    CORE    11.1.0.6.0      Production
    TNS for 32-bit Windows: Version 11.1.0.6.0 - Production
    NLSRTL Version 11.1.0.6.0 - Production
    SQL> set timing on
    SQL> set autot trace exp
    SQL> SELECT distinct  D.deptno, D.dname
      2        FROM     scott.dept D,scott.emp E
      3  where e.deptno=d.deptno
      4  order by d.deptno;
    Elapsed: 00:00:00.12
    Execution Plan
    Plan hash value: 925733878
    | Id  | Operation                     | Name    | Rows  | Bytes | Cost (%CPU)| T
    ime     |
    |   0 | SELECT STATEMENT              |         |     9 |   144 |     7  (29)| 0
    0:00:01 |
    |   1 |  SORT UNIQUE                  |         |     9 |   144 |     7  (29)| 0
    0:00:01 |
    |   2 |   MERGE JOIN                  |         |    14 |   224 |     6  (17)| 0
    0:00:01 |
    |   3 |    TABLE ACCESS BY INDEX ROWID| DEPT    |     4 |    52 |     2   (0)| 0
    0:00:01 |
    |   4 |     INDEX FULL SCAN           | PK_DEPT |     4 |       |     1   (0)| 0
    0:00:01 |
    |*  5 |    SORT JOIN                  |         |    14 |    42 |     4  (25)| 0
    0:00:01 |
    |   6 |     TABLE ACCESS FULL         | EMP     |    14 |    42 |     3   (0)| 0
    0:00:01 |
    Predicate Information (identified by operation id):
       5 - access("E"."DEPTNO"="D"."DEPTNO")
           filter("E"."DEPTNO"="D"."DEPTNO")
    SQL>
    SQL> SELECT distinct  D.deptno, D.dname
      2        FROM     scott.dept D,scott.emp E
      3  where e.deptno=d.deptno
      4  order by d.deptno;
        DEPTNO DNAME
            10 ACCOUNTING
            20 RESEARCH
            30 SALES
    Elapsed: 00:00:00.04
    SQL>So CBO did what we asked it do so.It made a full sort merge join.Now there is nothing wrong in it.There is no intelligence added by CBO to it.So now what, the query looks okay isn't it.If the answer is yes than let's finish the talk here.If no than we proceed further.
    We deliberately used the term "atleast" here.This would govern that we are not looking for entirely matching both the sources, emp and dept.Any matching result should solve our query's result.So , with "our knowledge" , we know that Exist can do that.Let's write teh query by it and see,
    SQL> SELECT   D.deptno, D.dname
      2        FROM     scott.dept D
      3          WHERE    EXISTS
      4                 (SELECT 1
      5                  FROM   scott.emp E
      6                  WHERE  E.deptno = D.deptno)
      7        ORDER BY D.deptno;
        DEPTNO DNAME
            10 ACCOUNTING
            20 RESEARCH
            30 SALES
    Elapsed: 00:00:00.00
    SQL>Wow, that's same but there is a small difference in the timing.Note that I did run the query several times to elliminate the physical reads and recursive calls to effect the demo. So its the same result, let's see the plan.
    SQL> SELECT   D.deptno, D.dname
      2        FROM     scott.dept D
      3          WHERE    EXISTS
      4                 (SELECT 1
      5                  FROM   scott.emp E
      6                  WHERE  E.deptno = D.deptno)
      7        ORDER BY D.deptno;
    Elapsed: 00:00:00.00
    Execution Plan
    Plan hash value: 1090737117
    | Id  | Operation                    | Name    | Rows  | Bytes | Cost (%CPU)| Ti
    me     |
    |   0 | SELECT STATEMENT             |         |     3 |    48 |     6  (17)| 00
    :00:01 |
    |   1 |  MERGE JOIN SEMI             |         |     3 |    48 |     6  (17)| 00
    :00:01 |
    |   2 |   TABLE ACCESS BY INDEX ROWID| DEPT    |     4 |    52 |     2   (0)| 00
    :00:01 |
    |   3 |    INDEX FULL SCAN           | PK_DEPT |     4 |       |     1   (0)| 00
    :00:01 |
    |*  4 |   SORT UNIQUE                |         |    14 |    42 |     4  (25)| 00
    :00:01 |
    |   5 |    TABLE ACCESS FULL         | EMP     |    14 |    42 |     3   (0)| 00
    :00:01 |
    Predicate Information (identified by operation id):
       4 - access("E"."DEPTNO"="D"."DEPTNO")
           filter("E"."DEPTNO"="D"."DEPTNO")Can you see a keyword called Semi here? This means that Oralce did make an equi join but not complete.Compare the bytes/rows returned from this as well as cost with the first query.Can you notice the difference?
    So what do we get from all this?You asked that if CBO becomes so smart, won't we need developers/dbas at that time?The answer is , what one wants to be, a monkey or an astranaut? Confused,read this,
    http://www.method-r.com/downloads/doc_download/6-the-oracle-advisors-from-a-different-perspective-karen-morton
    So it won't matter how much CBO would become intelligent, there will be still limitations to where it can go, what it can do.There will always be a need for a human to look all the automations.Rememember even the most sofisticated system needs some button to be pressed to get it on which is done by a human hand's finger ;-).
    Happy new year!
    HTH
    Aman....

  • Report with multiplying columns  and WITH clause

    Hello
    I saw sth strange in my report. I assume that it could happens very often.
    I have report with few columns which two of them ar most complicated (many joins subqueries aggreagations on joined values etc.) These two columns (i.e C3,C4) should be multiplied (C3*C4).
    When i do pure report without multiplying only columns C1,C2,C3,C4 everything is ok - duration about 15 sec. but... when I put next column on report which multiply these columns (in Answers C5=C3*C4)
    I wait 3-4 minutes and my database hungs :(. After investigation I saw that in first case to databese goes pure "SELECT" statement it means:
    "Select ... as C1, ... as C2, max(...) as C3, sum(xxx)... C4 from yyy,sss,ttt WHERE aaa"
    but in second case BI uses WITH clause it means:
    WITH SAWITH0 AS
    ( Select ... as C1, ... as C2, max(...) as C3, sum(xxx)... C4 from yyy,sss,ttt WHERE aaa )
    SELECT SAWITH0.C1 as C1,
    SAWITH0.C2 as C2,
         SAWITH0.C3 as C3,
         SAWITH0.C4 as C4,
         SAWITH0.C3*SAWITH0.C4 as C5 FROM SSS
    and this statement is long runninq query and kills my database :(.
    I checked that SQL like this:
    Select ... as C1, ... as C2, max(...) as C3, sum(xxx)... C4, max(...)*sum(xxx)... As C5 from yyy,sss,ttt WHERE aaa" -
    runs few times faster than that above
    I know that I can do this multiply in business model layer but sometimes users can multiply(or other operations) on columns in reports without my knowledge and it kills my db :(. Where is bug? Why SQLs with WITH clause takes so much db time?
    Thank you for each kind of help

    WITH clause or Subquery Factoring allows the set of data to be reused multiple times within the SQL. Oracle will usually materialize the data into a temporary table (you will see it if you take an explain plan of the SQL).
    I would be surprised if it was the actual WITH clause that was causing the performance issue, however you can test this by turning the WITH clause feature off. Go to the Physical model, right mouse click on your Database > Properties > Features Tab, scroll down to WITH_CLAUSE_SUPPORTED and switch it off.
    I'd be interested to know if you do see actual improvement.
    Good Luck.

  • WITH clause in reports

    Just a quick question about Reports 10g, does it support queries using the WITH clause? i.e.
    WITH alias as (subquery)
    SELECT col1, col2...
    FROM aliasI can't find anything on the documentation on the OTN site. Reports 9iR2 croaks with this unfortunately.
    Regards,
    Steve Rooney

    That is what I have had to do. I wanted to use the WITH clause because subquery has to be done twice so that I can perform some arithmetic on the result sets. Using the WITH construct I only need to define subquery once and re-use the result set; as a result the version using the WITH clause runs twice as fast in SQL*Plus as the way I have implemented the inline views.
    Thanks anyway.
    Regards,
    Steve Rooney

  • With Clause in Pro*C?

    Is it possible to use version 9's with clause (aka
    subquery factoring) within pro*C? Queries that work
    fine in SQL*Plus cause the pre-compiler to fail. For
    example:
    SQL> with test as (select 1 one from dual)
    2 select * from test
    3 /
    ONE
    1
    Taking the same query and embedding it in a Pro*C program,
    produces the following results:
    EXEC SQL
    with test as (select 1 one from dual)
    SELECT *
    INTO :n
    FROM test;
    $ proc ora_test.pc
    Pro*C/C++: Release 9.2.0.5.0 - Production on Mon Dec 20 13:27:16 2004
    Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved.
    System default option values taken from: /ora/product/9.2.0/precomp/admin/pcscfg.cfg
    Syntax error at line 20, column 7, file ora_test.pc:
    Error at line 20, column 7 in file ora_test.pc
    with test as (select 1 one from dual)
    ......1
    PCC-S-02201, Encountered the symbol "with" when expecting one of the following:
    for, register, at, close, commit, connect, declare, describe,
    execute, fetch, open, prepare, rollback, select, whenever,
    alter, audit, comment, create, delete, drop, get, grant,
    insert, lock, noaudit, rename, revoke, set, update, validate,
    arraylen, allocate, cache, call, collection, context,
    deallocate, enable, free, lob, object, savepoint, analyze,
    explain, truncate,
    The symbol "alter," was substituted for "with" to continue.
    Parser error at line 22, column 15, file ora_test.pc:
    Error at line 22, column 15 in file ora_test.pc
    INTO :n
    ..............1
    PCC-S-02206, Host variables are not permitted within a DDL statement
    Error at line 0, column 0 in file ora_test.pc
    PCC-F-02102, Fatal error while doing C preprocessing

    I suppose that the 'with clause ' is a new feature of ORACLE9 ? Well, lets dive in the fabulous world of ORACLE development :
    When the parser of ORACLE9 has been enhanced to accept ORACLE9 new features and syntax (especially the SQL1999 join syntax), the parser of PRO*C and PRO*Cobol still stayed at the ORACLE8 syntax level. The parser is at the Precompiler side.
    This means that you have NO CHANCE to even precompile a ORACLE9 syntax SQL statement with any precompiler tool.
    This is not a bug (from metalink) because the Oracle Development project for the new parser has not been started yet. I the product is not developped, it is not a bug , and i understand that they cannot correct the flaw.
    This is not corrected in any known ORACLE10 version - just because the project has not yet started !!!
    The only workaround that i have found consists in using a View which contains the syntax. This works fine for JOIN queries, i do not have tested for the 'with clause'.
    Maybe other workarounds available at the metalink side.
    Regards
    Frederic

  • WITH clause unexpectedly causes ORA-00942 in Reports Builder

    I'm posting this in the hope that:
    a) My workaround might help someone if they ever run into the same problem, and/or,
    b) Someone might have a better workaround.
    The problem is that I get unexpected ORA-00942 (table or view does not exist) errors when I try to set the SQL Query Statement property of a Query object in Reports Builder to certain SELECT statements that contain a WITH clause (aka subquery factoring clause).
    For example, the following SELECT statement executes as expected in SQL*Plus...
    SQL> WITH
      2      SUB_QUERY AS
      3      (
      4          SELECT
      5              1 AS X
      6          FROM
      7              DUAL
      8      )
      9  SELECT
    10      INLINE_VIEW.X
    11  FROM   
    12      (
    13          SELECT
    14              NESTED_INLINE_VIEW.X
    15          FROM
    16              (
    17                  SELECT
    18                      SUB_QUERY.X
    19                  FROM
    20                      SUB_QUERY
    21              ) NESTED_INLINE_VIEW
    22      ) INLINE_VIEW;
             X
             1...but when I try to use it as the SQL Query Statement for a Query object in Reports Builder, I get the following error:
    ORA-00942: table or view does not exist
    ==>SUB_QUERY
    My Reports Builder version is 10.1.2.0.2 version and my database version is 10.2.0.3.0.
    The "real" query I have been trying to use is much more complex than this -- this is just the simplest statement I have been able to come up with that causes the problem. In fact, I have some queries that have a similar structure (a WITH clause subquery referenced inside a nested inline view, along with some other things), but strangely do not cause the problem.
    I spent some time researching the problem on Google and Metalink but did not come up with any satisfactory answers. The problem sounds similar to bug 3896963, but bug 3896963 involved UNION ALL, and is supposedly fixed in my version(s).
    I tried various ways of restructuring my "real" query, but with no success -- it's going to be hard to get rid of the WITH clauses. As a "wild guess", I tried various hints (MATERIALIZE, NO_PUSH_PRED, NO_MERGE), again with no success.
    I ended up working around the problem by creating a database package with a function that returns a REF CURSOR based on the query, and then used that in a REF CURSOR query in Reports Builder. It might not be a very elegant workaround, but it works. I just wish I had "given up" and tried it sooner -- I might have saved myself some grief.

    Well, for what it's worth, I didn't end up using a REF CURSOR query after all because...
    If I ran a REP file based on a REF CURSOR query against a different database, or if I ran the REP file after the database package had been dropped and re-created, it failed with the following error:
    REP-8: Run time error in the PL/SQL development environment (DE).
    PDE-PSD001 Could not resolve reference to <Unknown Program Unit> while loading <Unknown> <Unknown>.
    REP-0008: Unexpected memory error while initializing preferences.
    It seems that Reports "binds" the REP file to the timestamp of the database package that defines the REF CURSOR type in order to validate the package at run time. If the timestamp is different, running the REP file will fail with this error. This is apparently bug 1275333 and is described in Metalink Note 272936.1.
    The bug reference and Metalink Note offerred the following workarounds:
    1. Export the database schema that contains the package from one database and import it into the other.
    In some versions, import and export preserve the timestamp, so this would avoid the problem. I didn't try this because it would not be a practical workaround in my situation (upgrade vs. new install).
    2. Recompile the package and manually set the timestamp using the seemingly undocumented ALTER PACKAGE...COMPILE BODY REUSE SETTINGS TIMESTAMP... syntax.
    I didn't try this because I didn't like the idea of having to: a) rely on an undocumented feature, and, b) manually keep track and maintain the timestamps of all the affected packages across several databases (e.g., development, test, and production).
    3. Put the package into a Reports library or into the report itself.
    This didn't work for me because Reports does not understand WITH clauses in PL/SQL. For example, with the example query in my previous post, I get an error like this:
    Error 103 at line {line defining name of factored subquery}, column {first column in line defining name of factored subquery}
    Encountered the symbol "SUB_QUERY" when expecting one of the following:
    &lt;a SQL statement&gt;
    4. Use an RDF file instead of a REP file.
    I didn't use this workaround because I wanted to protect the design of the report by using a REP file instead of an RDF file.
    So instead, I:
    1. Created a database package containing a pipelined function that returned the results of the WITH clause query that Reports did not "understand".
    2. Used an SQL query in my report of the form
    SELECT * FROM TABLE(MY_PACKAGE.MY_PIPELINED_FUNCTION(arg1, arg2, ...))
    I can drop and re-create the package and run the REP file against another database both without leading to the REP-8 error.

  • RESTICTIONS ON ORDER BY CLAUSE

    Can someone clear my doubts.I find it in DOCS but didn't succeded.Where it is written ?Please Explain me.
    Can We use ORDER BY CLAUSE in SubQuery ?
    Thanks.
    KarTiK.

    No,
    Even though It wont work..
    Findout yourself..
    SQL> select ename,sal
      2  from (select a.*,rownum s
      3        from emp a
      4        order by sal desc)
      5  where s = &rnk
      6  /
    Enter value for rnk: 4
    old   5: where s = &rnk
    new   5: where s = 4
    ENAME             SAL
    JONES            2975
    SQL> /
    Enter value for rnk: 3
    old   5: where s = &rnk
    new   5: where s = 3
    ENAME             SAL
    WARD             1250
    SQL> /
    Enter value for rnk: 1
    old   5: where s = &rnk
    new   5: where s = 1
    ENAME             SAL
    SMITH             800                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • Where can i get documentation on WITH clause?

    DB version:10gR2
    In OTN forums, i always see WITH clause being used to generate sample data, like the one used in the following thread
    How do I ORDER BY here?
    with data as
      select 666 as emp_id, 'JobA' as job_name, 'test_emp' as emp_name, 'test_team' as team, '08:00-11:48' as date_1, '07:00-08:00' as date_2, '08:00-11:48' as date_3
      from dual
      union all
      select 666 as emp_id, 'JobA' as job_name, 'test_emp' as emp_name, 'test_team' as team, '07:00-08:00' as date_1, null as date_2, '12:00-15:36' as date_3
      from dual
      union all
    .I want to know more about WITH clause, but i couldn't find this in Oracle Documentation(SQL Reference 10g Release 2
    Part No.B14200-02). Any idea where i could read about the basics, restrictions of use,..etc on WITH clause?

    Subquery factoring clause in the SELECT syntax...
    http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_10002.htm#SQLRF01702

  • CBO refuses hint (sometimes)

    Sometimes, the CBO does not take hints. Can anyone explain it?
    SQL:
    SELECT * FROM v_osi_child v1 WHERE mainuuid IN (SELECT uuid FROM ot_sys_index_org v2 WHERE mainuuid IN(:p1))v_osi_child is a view which union-alls about 50 tables. ot_sys_index_org is here only used for getting some mainuuids.
    The statement itself is free of sense :)
    Explain plan:
    | Id  | Operation            | Name                    | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT     |                         |     4 | 17252 |   402K  (1)| 01:20:31 |
    |*  1 |  HASH JOIN           |                         |     4 | 17252 |   402K  (1)| 01:20:31 |
    |*  2 |   INDEX RANGE SCAN   | PK_OTSYSINDEX           |     4 |   340 |     4   (0)| 00:00:01 |
    |   3 |   VIEW               | V_OSI_CHILD             |    56M|   223G|   402K  (1)| 01:20:27 |
    |   4 |    UNION-ALL         |                         |       |       |            |          |
    |   5 |     TABLE ACCESS FULL| FL_ALLG_BENUTZERDATEN   | 16797 |  1295K|   105   (0)| 00:00:02 |
    |   6 |     TABLE ACCESS FULL| FL_BERATUNG             |    17 |  1343 |     3   (0)| 00:00:01 |
    |   7 |     TABLE ACCESS FULL| PA_KBIVBI               | 16797 |  1295K|   105   (0)| 00:00:02 |
    ...This statement needs more than 10 minutes.
    Inserting a hint:
    SELECT /*+ push_pred(v1) */ * FROM v_osi_child v1 WHERE mainuuid IN (SELECT uuid FROM ot_sys_index_org v2 WHERE mainuuid IN(:p1));Explain plan:
    | Id  | Operation                      | Name                       | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT               |                            |     4 | 17852 | 12747   (1)| 00:02:33 |
    |   1 |  NESTED LOOPS                  |                            |     4 | 17852 | 12747   (1)| 00:02:33 |
    |*  2 |   INDEX RANGE SCAN             | PK_OTSYSINDEX              |     4 |   532 |     4   (0)| 00:00:01 |
    |   3 |   VIEW                         | V_OSI_CHILD                |     1 |  4330 |  3186   (1)| 00:00:39 |
    |   4 |    UNION ALL PUSHED PREDICATE  |                            |       |       |            |          |
    |   5 |     TABLE ACCESS BY INDEX ROWID| FL_ALLG_BENUTZERDATEN      |     1 |    79 |     2   (0)| 00:00:01 |
    |*  6 |      INDEX RANGE SCAN          | OSI_FLALLGBENUTZE_MAINUUID |     1 |       |     1   (0)| 00:00:01 |
    |   7 |     TABLE ACCESS BY INDEX ROWID| FL_BERATUNG                |     1 |    79 |     2   (0)| 00:00:01 |
    |*  8 |      INDEX RANGE SCAN          | OSI_FLBERATUNG_MAINUUID    |     1 |       |     1   (0)| 00:00:01 |
    |   9 |     TABLE ACCESS BY INDEX ROWID| PA_KBIVBI                  |     1 |    79 |     2   (0)| 00:00:01 |
    |* 10 |      INDEX RANGE SCAN          | OSI_PAKBIVBI_MAINUUID      |     1 |       |     1   (0)| 00:00:01 |
    |  11 |     TABLE ACCESS BY INDEX ROWID| FL_K_AKTIVITAET            |     1 |   100 |     2   (0)| 00:00:01 |
    |* 12 |      INDEX RANGE SCAN          | OSI_FLKAKTIVITAET_MAINUUID |     1 |       |     1   (0)| 00:00:01 |
    ...Well, using the index on mainuuids is realy a good idea, if the estimated resultset of the subquery are about 4 rows.
    Costs are decreased from 402k to 12747.
    Query runs in a second.
    Now, lets modify the subquery a little bit. Again, the estimated result of the subquery are 4 rows:
    SELECT * FROM v_osi_child v1 WHERE mainuuid IN (SELECT mainuuid FROM ot_sys_index_org v2 WHERE value IN(:p1));Explain plan:
    | Id  | Operation            | Name                    | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT     |                         |     4 | 17104 |   402K  (1)| 01:20:31 |
    |*  1 |  HASH JOIN RIGHT SEMI|                         |     4 | 17104 |   402K  (1)| 01:20:31 |
    |*  2 |   INDEX RANGE SCAN   | IX_OT_SYS_INDEX01       |     4 |   192 |     5   (0)| 00:00:01 |
    |   3 |   VIEW               | V_OSI_CHILD             |    56M|   223G|   402K  (1)| 01:20:27 |
    |   4 |    UNION-ALL         |                         |       |       |            |          |
    |   5 |     TABLE ACCESS FULL| FL_ALLG_BENUTZERDATEN   | 16797 |  1295K|   105   (0)| 00:00:02 |
    |   6 |     TABLE ACCESS FULL| FL_BERATUNG             |    17 |  1343 |     3   (0)| 00:00:01 |
    |   7 |     TABLE ACCESS FULL| PA_KBIVBI               | 16797 |  1295K|   105   (0)| 00:00:02 |
    |   8 |     TABLE ACCESS FULL| FL_K_AKTIVITAET         |    26 |  2600 |     3   (0)| 00:00:01 |
    ...Well, almost the same values...
    Now, use the same hint:
    SELECT /*+ push_pred(v1) */ * FROM v_osi_child v1 WHERE mainuuid IN (SELECT mainuuid FROM ot_sys_index_org v2 WHERE value IN(:p1));Explain plan:
    | Id  | Operation            | Name                    | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT     |                         |     4 | 17104 |   402K  (1)| 01:20:31 |
    |*  1 |  HASH JOIN RIGHT SEMI|                         |     4 | 17104 |   402K  (1)| 01:20:31 |
    |*  2 |   INDEX RANGE SCAN   | IX_OT_SYS_INDEX01       |     4 |   192 |     5   (0)| 00:00:01 |
    |   3 |   VIEW               | V_OSI_CHILD             |    56M|   223G|   402K  (1)| 01:20:27 |
    |   4 |    UNION-ALL         |                         |       |       |            |          |
    |   5 |     TABLE ACCESS FULL| FL_ALLG_BENUTZERDATEN   | 16797 |  1295K|   105   (0)| 00:00:02 |
    |   6 |     TABLE ACCESS FULL| FL_BERATUNG             |    17 |  1343 |     3   (0)| 00:00:01 |
    |   7 |     TABLE ACCESS FULL| PA_KBIVBI               | 16797 |  1295K|   105   (0)| 00:00:02 |
    ...Nothing has changed.
    I can't explain it. It seems to be an oracle-bug...
    Release: 11.1.0.7.0 - 64bit Production
    OS: RHEL 5.3

    Ulrich Weiss wrote:
    All this is readable from the explain plans.I don't know the reason behind this behaviour and I don't have a 11g version to test on, but I found similar observations on a 10g database. A small yet complete reproducible test case always helps. Here is mine:
    SQL> select * from v$version ;
    BANNER
    Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi
    PL/SQL Release 10.2.0.4.0 - Production
    CORE     10.2.0.4.0     Production
    TNS for Solaris: Version 10.2.0.4.0 - Production
    NLSRTL Version 10.2.0.4.0 - Production
    SQL> drop view v_t ;
    View dropped.
    SQL> drop table t1 purge ;
    Table dropped.
    SQL> drop table t purge ;
    Table dropped.
    SQL> create table t nologging as select * from all_objects ;
    Table created.
    SQL> create table t1 nologging as select * from t where rownum <= 1000 ;
    Table created.
    SQL> create or replace view v_t as
      2  select * from t where object_type = 'PACKAGE'
      3  union all
      4  select * from t where object_type = 'PACKAGE BODY' ;
    View created.
    SQL> explain plan for select * from v_t where object_id in (select object_id from t1 where owner = '
      2  SYS') ;
    Explained.
    SQL> exec dbms_stats.gather_table_stats(user, 'T') ;
    PL/SQL procedure successfully completed.
    SQL> exec dbms_stats.gather_table_stats(user, 'T1') ;
    PL/SQL procedure successfully completed.
    SQL> explain plan for select * from v_t where object_id in (select object_id from t1 where owner = 'SYS') ;
    Explained.
    SQL> select * from table(dbms_xplan.display) ;
    PLAN_TABLE_OUTPUT
    Plan hash value: 443534535
    | Id  | Operation            | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT     |      |     2 |   274 |   333   (2)| 00:00:04 |
    |*  1 |  HASH JOIN RIGHT SEMI|      |     2 |   274 |   333   (2)| 00:00:04 |
    |*  2 |   TABLE ACCESS FULL  | T1   |   893 |  8037 |     5   (0)| 00:00:01 |
    |   3 |   VIEW               | V_T  |  2055 |   256K|   327   (2)| 00:00:04 |
    |   4 |    UNION-ALL         |      |       |       |            |          |
    |*  5 |     TABLE ACCESS FULL| T    |  1067 |    97K|   164   (2)| 00:00:02 |
    |*  6 |     TABLE ACCESS FULL| T    |   988 | 92872 |   164   (2)| 00:00:02 |
    Predicate Information (identified by operation id):
       1 - access("OBJECT_ID"="OBJECT_ID")
       2 - filter("OWNER"='SYS')
       5 - filter("OBJECT_TYPE"='PACKAGE')
       6 - filter("OBJECT_TYPE"='PACKAGE BODY')
    21 rows selected.
    SQL> explain plan for select /*+ push_pred(v_t) */ * from v_t where object_id in (select object_id from t1 where owner = 'SYS') ;
    Explained.
    SQL> select * from table(dbms_xplan.display) ;
    PLAN_TABLE_OUTPUT
    Plan hash value: 443534535
    | Id  | Operation            | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT     |      |     2 |   274 |   333   (2)| 00:00:04 |
    |*  1 |  HASH JOIN RIGHT SEMI|      |     2 |   274 |   333   (2)| 00:00:04 |
    |*  2 |   TABLE ACCESS FULL  | T1   |   893 |  8037 |     5   (0)| 00:00:01 |
    |   3 |   VIEW               | V_T  |  2055 |   256K|   327   (2)| 00:00:04 |
    |   4 |    UNION-ALL         |      |       |       |            |          |
    |*  5 |     TABLE ACCESS FULL| T    |  1067 |    97K|   164   (2)| 00:00:02 |
    |*  6 |     TABLE ACCESS FULL| T    |   988 | 92872 |   164   (2)| 00:00:02 |
    Predicate Information (identified by operation id):
       1 - access("OBJECT_ID"="OBJECT_ID")
       2 - filter("OWNER"='SYS')
       5 - filter("OBJECT_TYPE"='PACKAGE')
       6 - filter("OBJECT_TYPE"='PACKAGE BODY')
    21 rows selected.
    SQL> explain plan for select v_t.* from v_t, t1 where v_t.object_id = t1.object_id and t1.owner = 'SYS' ;
    Explained.
    SQL> select * from table(dbms_xplan.display) ;
    PLAN_TABLE_OUTPUT
    Plan hash value: 2725479221
    | Id  | Operation            | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT     |      |  1834 |   245K|   333   (2)| 00:00:04 |
    |*  1 |  HASH JOIN           |      |  1834 |   245K|   333   (2)| 00:00:04 |
    |*  2 |   TABLE ACCESS FULL  | T1   |   893 |  8037 |     5   (0)| 00:00:01 |
    |   3 |   VIEW               | V_T  |  2055 |   256K|   327   (2)| 00:00:04 |
    |   4 |    UNION-ALL         |      |       |       |            |          |
    |*  5 |     TABLE ACCESS FULL| T    |  1067 |    97K|   164   (2)| 00:00:02 |
    |*  6 |     TABLE ACCESS FULL| T    |   988 | 92872 |   164   (2)| 00:00:02 |
    Predicate Information (identified by operation id):
       1 - access("V_T"."OBJECT_ID"="T1"."OBJECT_ID")
       2 - filter("T1"."OWNER"='SYS')
       5 - filter("OBJECT_TYPE"='PACKAGE')
       6 - filter("OBJECT_TYPE"='PACKAGE BODY')
    21 rows selected.
    SQL> explain plan for select /*+ push_pred(v_t) */ v_t.* from v_t, t1 where v_t.object_id = t1.object_id and t1.owner = 'SYS' ;
    Explained.
    SQL> select * from table(dbms_xplan.display) ;
    PLAN_TABLE_OUTPUT
    Plan hash value: 3926093524
    | Id  | Operation                     | Name | Rows  | Bytes | Cost (%CPU)| Time     |
    |   0 | SELECT STATEMENT              |      |  1834 |   263K|   292K  (2)| 00:58:28 |
    |   1 |  NESTED LOOPS                 |      |  1834 |   263K|   292K  (2)| 00:58:28 |
    |*  2 |   TABLE ACCESS FULL           | T1   |   893 | 11609 |     5   (0)| 00:00:01 |
    |   3 |   VIEW                        | V_T  |     1 |   134 |   327   (2)| 00:00:04 |
    |   4 |    UNION ALL PUSHED PREDICATE |      |       |       |            |          |
    |*  5 |     TABLE ACCESS FULL         | T    |     1 |    94 |   164   (2)| 00:00:02 |
    |*  6 |     TABLE ACCESS FULL         | T    |     1 |    94 |   164   (2)| 00:00:02 |
    Predicate Information (identified by operation id):
       2 - filter("T1"."OWNER"='SYS')
       5 - filter("OBJECT_ID"="T1"."OBJECT_ID" AND "OBJECT_TYPE"='PACKAGE')
       6 - filter("OBJECT_ID"="T1"."OBJECT_ID" AND "OBJECT_TYPE"='PACKAGE BODY')
    20 rows selected.As you can see, the PUSH_PRED hint is ignored when I use the IN clause with subquery.
    I believe this is same as what you are experiencing. However, when I change the sql to use
    a JOIN (instead of subquery), the hint is not ignored.
    p.s. I hope my JOIN query is semantically equivalent to IN..SUBQUERY.

  • Combine two select query

    Hi All,
    Many thanks for all kind support so far.
    I have two report (sql query)
    I want to add both the sql query
    1st sql query
    select distinct(a.item_number)
          ,a.quantity - b.quantity
    from QUANTITY_ONHAND_ATP a,BACKLOG_ATP_LT_CW b
    where a.item_number = b.item_number
    order by item_number2nd sql query
    select distinct(wb.item_number)
           ,wb.quantity - be.quantity
           ,a.quantity - b.quantity
    from BACKLOG_WEEK_BEFORE_ATP wb
        ,BACKLOG_ATP_ET_CW be
        ,BACKLOG_WEEK_AFTER_ATP a
        ,BACKLOG_ATP_GT_CW b
    where wb.item_number = be.item_number
       and a.item_number = b.item_number
       and wb.item_number = a.item_number
       and be.item_number = a.item_number
       and wb.item_number = b.item_number
       and be.item_number = b.item_number
    order by wb.ITEM_NUMBERIn 1st sql query i have 129 records and in 2nd sql query i have 14 records. I want to combine these two sql query. If the item_number of 1st sql query is not there in 2nd one then display it as it is in 1st sql only.
    Any help how to do that.
    Regards

    Hi,
    the gerenal approach to combine the results of two or more SQL queries would be the
    UNION / UNION ALL
    INTERSECT
    MINUS
    SQL clauses. Union just combines the results; INTERSECT will return the rows which are present
    in both result sets and MINUS will reduce the first result set by the rows of the second.
    Basically it works like this
    select * from emp where deptno = 10
    union all(
    select * from empo where deptno = 20
    All the queries must have identical columns in the result set - same number of columns
    and the same data types. So you would have to add a column to your first SQL query ...
    select distinct(a.item_number) item_number,
    to_number(*,null*) first_value
    ,a.quantity - b.quantity second_value
    from QUANTITY_ONHAND_ATP a,BACKLOG_ATP_LT_CW b
    where a.item_number = b.item_number
    order by item_number
    and in the second query I'd recommend to use the same aliases ....
    Does this help
    -Carsten
    Deutschsprachige APEX-Community: Tipps, Tricks, Best Practice
    http://tinyurl.com/apexcommunity
    SQL und PL/SQL: Tipps, Tricks & Best Practice
    http://sql-plsql-de.blogspot.com
    Twitter: @cczarski

  • APEX report with Break columns and BI Publisher

    I am having an issue with APEX and using column breaks when printing to BI publisher.. It seems that when you write an APEX report that breaks on the 1st or 1st and 2nd columns, the grouping shows nicely in APEX, but when BI Publisher gets the XML data, and you do the same grouping using an RTF file, there is a group of rows with NO grouping info that occurs at the top of the report, then each group you expect has just ONE row..
    (Just giving this a bump to see anyone has an idea here..)
    Any suggestions?
    Thank you,
    Tony Miller
    Message was edited by:
    Tony Miller

    WITH clause or Subquery Factoring allows the set of data to be reused multiple times within the SQL. Oracle will usually materialize the data into a temporary table (you will see it if you take an explain plan of the SQL).
    I would be surprised if it was the actual WITH clause that was causing the performance issue, however you can test this by turning the WITH clause feature off. Go to the Physical model, right mouse click on your Database > Properties > Features Tab, scroll down to WITH_CLAUSE_SUPPORTED and switch it off.
    I'd be interested to know if you do see actual improvement.
    Good Luck.

  • 1Z0-051 exercises for preparing the exam

    Hello, I'm preparing for the 1Z0-051 exam and It could be useful for me some link o similar with exercises about SQL.
    Thanks in advance.
    Regards.

    What you are asking for and what the original poster was is 'guided practice'.  The only thing that really fits that description is lab exercises. Generally these are only created as part of a class.  I don't know of anyone that creates labs and puts them online.
    I always encourage candidates to load Oracle XE on their computer and practice with the topics covered on certification exams, If you have any certification book for 1Z0-051, it will have some SQL examples inside it.  They probably won't be labs which tell you exactly what to do in a step-by-step fashion. However, you can execute the same SQL on your machine if you have an Oracle instance.  The Oracle sample schemas are available online.  My study guides have a sample schema that can be downloaded from my website.  I believe the Oracle Press 051 book likewise has a schema (or possibly it uses the sample schemas).  Just typing in the examples straight from the book is a start.  You can then play with those examples -- varying them to see what works and what does not.  For example -- if an example shows a multi-table select the INNER JOIN syntax, take that SQL and modify it to the USING syntax or the NATURAL JOIN syntax.
    The 1Z0-051 exam is all about the capabilities and syntax of SQL... basically what can and cannot be done. Much of this is really memorization of the syntax and certain facts -- like what clauses a subquery can appear in. Executing working SQL and then modifying it to see what works and what does not can help to cement those facts in your memory.

Maybe you are looking for