Connect BY, Prior, Start clause

I want to understand how does the Connect BY, Prior, Start clause work, i mean the concept.
Please explain with an example.
I hope, my question is clear. Please help in solving the doubt as it is urgent.
Regards.

Here is the simple example you can find in a dept first traversal fashion the records come in mgr-emp hirarchy
SQL>SELECT * FROM EMP
  2  START WITH MGR IS NULL
  3  CONNECT BY PRIOR EMPNO = MGR;
     EMPNO ENAME      JOB              MGR HIREDATE         SAL       COMM     DEPTN
      7839 KING       PRESIDENT            17-NOV-81       5000                    1
      7566 JONES      MANAGER         7839 02-APR-81       2975                    2
      7788 SCOTT      ANALYST         7566 19-APR-87       3000                    2
      7876 ADAMS      CLERK           7788 23-MAY-87       1100                    2
      7902 FORD       ANALYST         7566 03-DEC-81       3000                    2
      7369 SMITH      CLERK           7902 17-DEC-80        800                    2
      7698 BLAKE      MANAGER         7839 01-MAY-81       2850                    3
      7499 ALLEN      SALESMAN        7698 20-FEB-81       1600                    3
      7521 WARD       SALESMAN        7698 22-FEB-81       1250                    3
      7654 MARTIN     SALESMAN        7698 28-SEP-81       1250                    3
      7844 TURNER     SALESMAN        7698 08-SEP-81       1500                    3
      7900 JAMES      CLERK           7698 03-DEC-81        950                    3
      7782 CLARK      MANAGER         7839 09-JUN-81       2450                    1
      7934 MILLER     CLERK           7782 23-JAN-82       1300                    1

Similar Messages

  • Join two Connect By Prior Start With trees and return only common records?

    Oracle 10g Release 2 (10.2)
    I have two tables that have tree structured data. The results, when running the queries individually are correct, however I need to join tree one to tree two in order to obtain only the common records between them.
    -- Tree one
    SELECT ip_entity_name, entity_code, hier_level, entity_parent
    FROM ip_hierarchy
    WHERE hier_level >= 3
    CONNECT BY PRIOR entity_code = entity_parent
    START WITH entity_code = 'MEWWD';
    -- Tree two
    SELECT ip_entity_name, entity_code, hier_level, entity_parent
    FROM ipt_hierarchy
    WHERE hier_level >= 3
    CONNECT BY PRIOR entity_code = entity_parent
    START WITH entity_code = 'IPNAM';
    As I understand, joins may not work with CONNECT BY/START WITH queries?
    Is a WITH clause an option?
    If at all possible, I don't want to put one select in a View database object and join against the other query.
    Thanks.

    Hi JTP51,
    You can use WITH clause or sub-query by using in-line view, without creating any view object in database.
    for example
    SELECT A.IP_ENTITY_NAME, A.ENTITY_CODE, ....
      FROM (SELECT IP_ENTITY_NAME, ENTITY_CODE, HIER_LEVEL, ENTITY_PARENT
              FROM IP_HIERARCHY
             WHERE HIER_LEVEL >= 3
            CONNECT BY PRIOR ENTITY_CODE = ENTITY_PARENT
             START WITH ENTITY_CODE = 'MEWWD') A,
           (SELECT IP_ENTITY_NAME, ENTITY_CODE, HIER_LEVEL, ENTITY_PARENT
              FROM IPT_HIERARCHY
             WHERE HIER_LEVEL >= 3
            CONNECT BY PRIOR ENTITY_CODE = ENTITY_PARENT
             START WITH ENTITY_CODE = 'IPNAM') B
    WHERE A. ENTITY_CODE = B. ENTITY_CODE
    AND ....Best regards,
    Zhxiang
    Edited by: zhxiangxie on Feb 2, 2010 5:35 PM

  • Oracle Virtual Machine Connect by Prior Problem

    Hi Friends ,
    In my company we have virtualization. this is new in our organization.
    oracle image have been taken and put in to virtual machine.(vmware).
    after that, procedure which has "connect by prior" start to create wrong output.
    please help us on what to do to correct problem given above.
    (my oracle version 10g)

    JAVAMAN2 wrote:
    simple sample:
    SELECT ROWNUM+2000-1 AS YIL FROM DUAL CONNECT BY ROWNUM <= 2010-2005 ORDER BY ROWNUM+2000-1 DESC;output on virtual machine
    2009,2008,2007,2006,2005
    output on real world
    2010,2009,2008,2007,2006,2005If that is really the output from that query, then both your virtual machine and your "real world" are broken. On all 4 versions of Oracle I have available, I get:
    SQL> SELECT ROWNUM + 2000 - 1 AS YIL
      2  FROM DUAL
      3  CONNECT BY ROWNUM <= 2010 - 2005
      4  ORDER BY ROWNUM + 2000 - 1 DESC;
           YIL
          2004
          2003
          2002
          2001
          2000Which is what I would expect given that 2010 - 2005 = 5.
    Perhaps if you showed an actual cut and paste from a sqlplus session on each machine someone might be able to help, however, I'm inclined to agree with sb92075 that it is a data issue in your real query.
    John

  • 'CONNECT BY PRIOR..START WITH'  clause  Usage

    Hi All,
    Could you please let me know the usage of 'connect by prior...start with' clause.
    I only know that it helps for hierarchial retrival,but not aware of details.
    Can someone provide the use with example for the same.
    On searching on the net,I have seen numerous examples but none of them could explain it properly and everywhere the same SCOTT/TIGER schemas EMP and MGR table's example is given which is not enough explanatory.
    Thanks in advance...
    Aashish S.

    suppose u need to get all employees in a company in a hirerchical manner
    ie presdent then mgrs
    then employeess reporting to them
    this can be done using connect by prior and start by
    select empname from emp
    connect by prior empno=mgrno
    start with mgrno is null

  • Hi all i am trying to use a Connect by prior clause

    Hi all,
    In my connect by prior clause i have a query. I want to pass the values to the query from my outer query. Can this be done in Oracle.Can any help me in this.Also Pasting my query for your reference
    SELECT rct2.trx_number
         , rctl2.customer_trx_line_id
         , fifs.flex_value_set_id
         , gcc.code_combination_id
         , ffvc.child_flex_value
         , ffvc.parent_flex_value
         , gcc.segment4
         , ffvc.description
         , ffvc.lvl
    FROM   ra_customer_trx_all rct2
          ,ra_customer_trx_lines_all rctl2
          ,ra_cust_trx_line_gl_dist_all rctlgd
          ,gl_code_combinations gcc
          , (SELECT     ffvv.flex_value_set_id
                      , ffvv.flex_value child_flex_value
                      , LEVEL lvl, ffvv.parent_flex_value
                      , ffvv.description
                   FROM fnd_flex_value_children_v ffvv
                  WHERE 1 = 1
                  START WITH  ffvv.flex_value = (SELECT 
          gcc.segment4
      FROM ra_customer_trx_all rct1,
           ra_customer_trx_lines_all rctl1,
           ra_cust_trx_line_gl_dist_all rctlgd,
           gl_code_combinations gcc
    WHERE rct1.customer_trx_id=rctl1.customer_trx_id
    AND rctl1.customer_trx_line_id=rctlgd.customer_trx_line_id
    AND  rct1.customer_trx_id=rctlgd.customer_trx_id
    AND rctlgd.account_class = 'REV'
    AND rctlgd.code_combination_id=gcc.code_combination_id
    AND rct1.trx_number            = :trx_number--Want to pass  rct2.trx_number here which is coming from outer query
    AND rctla.customer_trx_line_id = :trx_line_id)--Want to pass rctl2.customer_trx_line_id here which is coming from outer query
             CONNECT BY PRIOR ffvv.parent_flex_value = ffvv.flex_value  ) ffvc
          ,fnd_flex_value_sets s
          ,fnd_id_flex_segments fifs
          ,gl_ledgers l
    WHERE rct2.customer_trx_id           = rctl2.customer_trx_id
       AND rctl2.customer_trx_line_id   = rctlgd.customer_trx_line_id
       AND rct2.customer_trx_id          = rctlgd.customer_trx_id
       AND rctlgd.code_combination_id   = gcc.code_combination_id
       AND fifs.flex_value_set_id       = ffvc.flex_value_set_id
       AND fifs.application_id          = 101
       AND fifs.flex_value_set_id       = s.flex_value_set_id
       AND fifs.application_column_name = 'SEGMENT4'
       AND fifs.id_flex_code            = 'GL#'
       AND l.chart_of_accounts_id       = fifs.id_flex_num
       AND l.ledger_id                  = rct2.set_of_books_id
       AND rctlgd.account_class         = 'REV'
       AND rctl2.customer_trx_line_id   = :trx_line_id --Pass Trx id
       AND rct2.trx_number              = :trx_number  --Pass trx number

    Hello.
    "I created a function and added the above query to the function and passed the values  as parameters at both places"
    Well, this is not the best idea, because adding a function to your SQL will add many context switches (depending on the volume of your data) and may badly affect the CBO to choose not optimal execution plan. That's why it is better to avoid it if possible. Actually, I found no problem in using correlated subquery in the start with clause:
    with
        t1 as (
            select 1 as id, null as pid from dual
            union all
            select 2, 1 from dual
            union all
            select 3, 1 from dual
            union all
            select 5, 2 from dual
        t2 as (
            select 1 as t2id from dual
            union all
            select 2 as t2id from dual
    select lpad(' ', 2 * (level-1)) || t1.id as id
        , level
        , case when t1.id = connect_by_root t1.id then 'ROOT' else null end as ROOT
    from t1
    start with t1.id = (select t2.t2id from t2 where t2.t2id = t1.id)
    connect by prior t1.id = t1.pid
    order siblings by t1.id;
    ID
    LEVEL
    ROOT
    1
    1
    ROOT
      2
    2
        5
    3
      3
    2
    2
    1
    ROOT
      5
    2
    But, as Frank Kulash reasonably said, depending on the volume that you work with, it may probably be better to do the join before the connect by like this for example:
    with
        t1 as (
            select 1 as id, null as pid from dual
            union all
            select 2, 1 from dual
            union all
            select 3, 1 from dual
            union all
            select 5, 2 from dual
        t2 as (
            select 1 as t2id from dual
            union all
            select 2 as t2id from dual
    select lpad(' ', 2 * (level-1)) || t1.id as id
        , level
        , case when t1.id = connect_by_root t1.id then 'ROOT' else null end as ROOT
    from t1 left join t2 on t1.id = t2.t2id
    start with t2.t2id is not null
    connect by prior t1.id = t1.pid
    order siblings by t1.id
    ID
    LEVEL
    ROOT
    1
    1
    ROOT
      2
    2
        5
    3
      3
    2
    2
    1
    ROOT
      5
    2

  • Clarification regarding understanding of ORACLE CONNECT BY PRIOR Clause

    Dear All,
    I am trying to understand ORACLE CONNECT BY CLAUSE and I wrote a query to verify my understanding.
    I wrote the below two queries.
    select level, lpad('*',2*(level -1),'*') ||ename t_ename, sys_connect_by_path(ename,'/') enames, empno, mgr from emp
    --where empno =empno
    start with empno=7654
    --start with mgr is null
    connect by prior empno = mgr;
    LEVEL T_ENAME ENAMES EMPNO MGR
    1 MARTIN /MARTIN 7654 7698
    Explanation: Here Start with EMPNO=7654 Means, the root node is 7654. Connect BY PRIOR EMPNO=MGR Means--> For the empno=7654 are there any persons under him. IE. Mgr with 7654.
    select level, lpad('*',2*(level -1),'*') ||ename t_ename, sys_connect_by_path(ename,'/') enames, empno, mgr from emp
    --where empno =empno
    start with empno=7698
    --start with mgr is null
    connect by prior empno = mgr
    LEVEL T_ENAME ENAMES EMPNO MGR
    1 BLAKE /BLAKE 7698 7839
    2 **ALLEN /BLAKE/ALLEN 7499 7698
    2 **WARD /BLAKE/WARD 7521 7698
    2 **MARTIN /BLAKE/MARTIN 7654 7698
    2 **TURNER /BLAKE/TURNER 7844 7698
    2 **JAMES /BLAKE/JAMES 7900 7698
    Explanation: Here Start with EMPNO=7698 Means, the root node is 7698. Connect BY PRIOR EMPNO=MGR Means--> For the empno=7698 are there any persons under him. IE. Mgr with 7698.
    IS MY UNDERSTANDING OF CONNECT BY PRIOR IS CORRECT?
    Please correct me if I am wrong.
    Thanks,
    MK.

    Yes, you're right
    Regards,
    Sayan M.

  • Using START WITH and CONNECT BY PRIOR in a report

    Hi - I am using Oracle 9i and reports 10g. Does anyone know of a reason why running my sql in TOAD will produce the correct results, but the report is dropping records? I am using start with and connect by prior to build a hierarchy of linked records. The report is dropping the "child records" and only returning records from the route level.
    Thanks you for your help.

    Hi user574499
    Could u pls share us ur Query...?
    Regards,
    Abdetu...

  • Understanding multiple conditions in connect by prior clause Oracle

    Hi ,
    Can some one please explain me how to comprehend/understand  multiple conditions in connect by prior conditions with some example data.
    I am creating a table like this
    CREATE TABLE FAMiLY_TREE
    GRAND_FATHERID number,
    FATHER_ID number,
    SON_ID number,
    person_name varchar(20)
    INSERT INTO  FAMILY_TREE (GRAND_FATHERID ,FATHER_ID , SON_ID , PERSON_NAME ) VALUES
    (NULL, NULL , 5 , 'Mr X ' );
    INSERT INTO  FAMILY_TREE (GRAND_FATHERID ,FATHER_ID , SON_ID , PERSON_NAME ) VALUES
    (null, 5 , 6 , 'Dave' );
    INSERT INTO  FAMILY_TREE (GRAND_FATHERID ,FATHER_ID , SON_ID , PERSON_NAME ) VALUES
    (5, 6 , 7 , 'Vinny' );
    INSERT INTO  FAMILY_TREE (GRAND_FATHERID ,FATHER_ID , SON_ID , PERSON_NAME ) VALUES
    (5, 6 , 16 , 'Omy' );
    INSERT INTO  FAMILY_TREE (GRAND_FATHERID ,FATHER_ID , SON_ID , PERSON_NAME ) VALUES
    (5, 6 , 17 , 'Vijjy' );
    INSERT INTO  FAMILY_TREE (GRAND_FATHERID ,FATHER_ID , SON_ID , PERSON_NAME ) VALUES
    (6, 7 , 8 , 'Vicky' );
    INSERT INTO  FAMILY_TREE (GRAND_FATHERID ,FATHER_ID , SON_ID , PERSON_NAME ) VALUES
    (6, 7 , 9 , 'Varis' );
    INSERT INTO  FAMILY_TREE (GRAND_FATHERID ,FATHER_ID , SON_ID , PERSON_NAME ) VALUES
    (7, 8 , 10 , 'Vshnu' );
    INSERT INTO  FAMILY_TREE (GRAND_FATHERID ,FATHER_ID , SON_ID , PERSON_NAME ) VALUES
    (7, 8 , 11 , 'dyna' );
    INSERT INTO  FAMILY_TREE (GRAND_FATHERID ,FATHER_ID , SON_ID , PERSON_NAME ) VALUES
    (8, 10 , 14 , 'Marry' );
    INSERT INTO  FAMILY_TREE (GRAND_FATHERID ,FATHER_ID , SON_ID , PERSON_NAME ) VALUES
    (8, 10 , 15 , 'Mac' );
    INSERT INTO  FAMILY_TREE (GRAND_FATHERID ,FATHER_ID , SON_ID , PERSON_NAME ) VALUES
    (7, 9 , 12 , 'Garry' );
    INSERT INTO  FAMILY_TREE (GRAND_FATHERID ,FATHER_ID , SON_ID , PERSON_NAME ) VALUES
    (7, 9 , 13 , 'Ganny' );
    SELECT
    LPAD(' ', LEVEL*3) || PERSON_NAME FROM FAMILY_TREE
    START WITH SON_ID= 6
    CONNECT BY PRIOR SON_ID = FATHER_ID
    AND PRIOR FATHER_ID = GRAND_FATHERID ;
    SELECT
    LPAD(' ', LEVEL*3) || PERSON_NAME FROM FAMILY_TREE
    START WITH SON_ID= 6
    CONNECT BY PRIOR SON_ID = FATHER_ID ;
    Both These query return the same o/p
       Dave
          Vinny
             Vicky
                Vshnu
                   Marry
                   Mac
                dyna
             Varis
                Garry
                Ganny
          Omy
          Vijjy
    Can some one please explain me comprehension of both these query or give me a example where i can understand multiple connect by prior conditions
    Thanks

    Maybe (something to play with)
    with
    family_tree as
    (select 'Green' family,null ancestor,1 person,'Mr X' person_name,1900 born from dual union all
    select 'Green',1,2,'Dave',1920 from dual union all
    select 'Green',2,3,'Vinny',1940 from dual union all
    select 'Green',2,4,'Omy',1945 from dual union all
    select 'Green',2,5,'Vijjy',1950 from dual union all
    select 'Green',3,6,'Vicky',1960 from dual union all
    select 'Green',3,7,'Varis',1965 from dual union all
    select 'Green',6,8,'Vshnu',1980 from dual union all
    select 'Green',6,9,'Dyna',1985 from dual union all
    select 'Green',8,10,'Mary',2000 from dual union all
    select 'Green',8,11,'Mac',2005 from dual union all
    select 'Green',7,12,'Garry',1985 from dual union all
    select 'Green',7,13,'Ganny',1990 from dual union all
    select 'Brown',null,14,'Joe',1950 from dual union all
    select 'Brown',14,15,'Jim',1970 from dual union all
    select 'Brown',14,16,'Joy',1975 from dual union all
    select 'Brown',14,17,'Jay',1980 from dual union all
    select 'Brown',16,18,'Jack',1995 from dual union all
    select 'Brown',18,19,'Jake',2010 from dual union all
    select 'Brown',18,20,'Jess',2012 from dual
    select family,
           root_name||' ('||to_char(root_born)||')' "(FA/MO)THER",
           children
      from (select family,
                   root_born,
                   root_name,
                   ltrim(sys_connect_by_path(person_name||' ('||to_char(born)||')',', '),', ') children
              from (select family,
                           connect_by_root(person_name) root_name,
                           connect_by_root(born) root_born,
                           person_name,
                           born,
                           row_number() over (partition by family,connect_by_root(person_name) order by born) rn
                      from family_tree
                     where level = 2
                    connect by prior person = ancestor
             where connect_by_isleaf = 1
             start with rn = 1
            connect by prior root_name = root_name
                   and prior family = family
                   and prior rn + 1 = rn
    order by family desc,root_born
    Regards
    Etbin

  • Slow connect by prior ... start with subquery in 9i

    Has anyone come across a performance problem (compared to 8i) when using hierarchical queries where the START WITH list is generated by a subquery? The culprit seems to be an extra visit to the subquery block as part of the CONNECT BY WITH FILTERING operation.
    For example, take a simple tree structure:
    CREATE TABLE tree
    id NUMBER,
    parentid NUMBER
    CONSTRAINT tree_pk PRIMARY KEY (id)
    ...and a subquery - here just a table called sample with a subset of the ids from the tree table:
    CREATE TABLE sample
    id NUMBER,
    CONSTRAINT sample_pk PRIMARY KEY (id)
    ...with which to drive the start points of the treewalk:
    SELECT parentid, id, label
    FROM tree
    CONNECT BY PRIOR parentid = id
    START WITH id IN
    SELECT id FROM SAMPLE
    With the tables populated and analyzed, I get this from 8i:
    Execution Plan
    .0......SELECT STATEMENT Optimizer=CHOOSE (Cost=2 Card=1 Bytes=19)
    .1....0...CONNECT BY
    .2....1.....NESTED LOOPS (Cost=1 Card=1280 Bytes=10240)
    .3....2.......INDEX (FAST FULL SCAN) OF 'ID_PK' (UNIQUE) (Cost=1 Card=1280 Bytes=5120)
    .4....2.......INDEX (UNIQUE SCAN) OF 'TREE_PK' (UNIQUE)
    .5....1.....TABLE ACCESS (BY USER ROWID) OF 'TREE'
    .6....1.....TABLE ACCESS (BY INDEX ROWID) OF 'TREE' (Cost=2 Card=1 Bytes=19)
    .7....6.......INDEX (UNIQUE SCAN) OF 'TREE_PK' (UNIQUE) (Cost=1 Card=1)
    Statistics
    .....0..recursive calls
    .....4..db block gets
    .15687..consistent gets
    ....59..physical reads
    .....0..redo size
    223313..bytes sent via SQL*Net to client
    .38276..bytes received via SQL*Net from client
    ...343..SQL*Net roundtrips to/from client
    .....3..sorts (memory)
    .....0..sorts (disk)
    ..5120..rows processed
    and this is 9i:
    Execution Plan
    .0......SELECT STATEMENT Optimizer=CHOOSE (Cost=2 Card=1 Bytes=19)
    .1....0...CONNECT BY (WITH FILTERING)
    .2....1.....NESTED LOOPS
    .3....2.......NESTED LOOPS (Cost=2 Card=1280 Bytes=10240)
    .4....3.........INDEX (FAST FULL SCAN) OF 'ID_PK' (UNIQUE) (Cost=2 Card=1280 Bytes=5120)
    .5....3.........INDEX (UNIQUE SCAN) OF 'TREE_PK' (UNIQUE)
    .6....2.......TABLE ACCESS (BY USER ROWID) OF 'TREE'
    .7....1.....NESTED LOOPS
    .8....7.......BUFFER (SORT)
    .9....8.........CONNECT BY PUMP
    10....7.......TABLE ACCESS (BY INDEX ROWID) OF 'TREE' (Cost=2 Card=1 Bytes=19)
    11...10.........INDEX (UNIQUE SCAN) OF 'TREE_PK' (UNIQUE) (Cost=1 Card=20480)
    12....1.....INDEX (UNIQUE SCAN) OF 'SAMPLE_PK' (UNIQUE) (Cost=1 Card=1 Bytes=4)
    Statistics
    .....1..recursive calls
    .....1..db block gets
    .20525..consistent gets
    ....72..physical reads
    ...120..redo size
    224681..bytes sent via SQL*Net to client
    .38281..bytes received via SQL*Net from client
    ...343..SQL*Net roundtrips to/from client
    .....9..sorts (memory)
    .....0..sorts (disk)
    ..5120..rows processed
    ..so, about another 5000 logical reads, corresponding to the extra access of the sample table at the bottom of the query plan. So instead of just visiting the START WITH subquery once, to kick off the treewalk, I seem to be revisiting it for every row returned. Not too bad if that happens to be a unique index scan as here but that's not always the case.
    I know I've got new options for re-writing this as a join under 9i, I'm just curious about those extra lookups and why they're necessary.
    Cheers - Andrew

    There is undocumented parameter in Oracle 9i "_old_connect_by_enabled"
    which controls the behavoiur of hierarchy queries in 9i and above:
    You can try to return to 8i behaviour using it:
    SQL> SELECT parentid, id
      2  FROM tree
      3  CONNECT BY PRIOR parentid = id
      4  START WITH id IN
      5  (
      6  SELECT id FROM SAMPLE
      7  )
      8  /
    Execution Plan
       0      SELECT STATEMENT Optimizer=ALL_ROWS (Cost=1 Card=1 Bytes=26)
       1    0   CONNECT BY (WITH FILTERING)
       2    1     TABLE ACCESS (BY INDEX ROWID) OF 'TREE' (TABLE)
       3    2       NESTED LOOPS (Cost=2 Card=1 Bytes=26)
       4    3         TABLE ACCESS (FULL) OF 'SAMPLE' (TABLE) (Cost=2 Card
              =1 Bytes=13)
       5    3         INDEX (UNIQUE SCAN) OF 'TREE_PK' (INDEX (UNIQUE)) (C
              ost=0 Card=1 Bytes=13)
       6    1     NESTED LOOPS
       7    6       BUFFER (SORT)
       8    7         CONNECT BY PUMP
       9    6       TABLE ACCESS (BY INDEX ROWID) OF 'TREE' (TABLE) (Cost=
              1 Card=1 Bytes=26)
      10    9         INDEX (UNIQUE SCAN) OF 'TREE_PK' (INDEX (UNIQUE)) (C
              ost=1 Card=1)
      11    1     TABLE ACCESS (FULL) OF 'TREE' (TABLE) (Cost=1 Card=1 Byt
              es=26)
      12    1     INDEX (UNIQUE SCAN) OF 'SAMPLE_PK' (INDEX (UNIQUE)) (Cos
              t=1 Card=1 Bytes=13)
    SQL> alter session set "_old_connect_by_enabled" = TRUE;
    Session altered.
    SQL> SELECT parentid, id
      2  FROM tree
      3  CONNECT BY PRIOR parentid = id
      4  START WITH id IN
      5  (
      6  SELECT id FROM SAMPLE
      7  )
      8  /
    Execution Plan
       0      SELECT STATEMENT Optimizer=ALL_ROWS (Cost=1 Card=1 Bytes=26)
       1    0   CONNECT BY
       2    1     NESTED LOOPS (Cost=2 Card=1 Bytes=26)
       3    2       TABLE ACCESS (FULL) OF 'SAMPLE' (TABLE) (Cost=2 Card=1
               Bytes=13)
       4    2       INDEX (UNIQUE SCAN) OF 'TREE_PK' (INDEX (UNIQUE)) (Cos
              t=0 Card=1 Bytes=13)
       5    1     TABLE ACCESS (BY USER ROWID) OF 'TREE' (TABLE)
       6    1     TABLE ACCESS (BY INDEX ROWID) OF 'TREE' (TABLE) (Cost=1
              Card=1 Bytes=26)
       7    6       INDEX (UNIQUE SCAN) OF 'TREE_PK' (INDEX (UNIQUE)) (Cos
              t=1 Card=1)
    Rgds.

  • Help me in understand connect By Prior

    Hi ,
    please help me in understand connect By Prior
    I did a sample example , but unale to follow , please explain
    How did it understand that KING shuld be displaed first .
    On wht basis the results are shown here ?
    SELECT empno,
    ename,
    job,
    mgr,
    hiredate,
    level
    FROM   emp
    START WITH mgr IS NULL
    CONNECT BY PRIOR empno = mgr
    7839     KING PRESIDENT      17-Nov-81     1
    7566     JONES MANAGER 7839     2-Apr-81     2
    7788     SCOTT ANALYST 7566     19-Apr-87     3
    7876     ADAMS CLERK 7788     23-May-87     4
    7902     FORD ANALYST 7566     3-Dec-81     3
    7369     SMITH CLERK 7902     17-Dec-80     4
    7698     BLAKE MANAGER 7839     1-May-81     2
    7499     ALLEN SALESMAN 7698     20-Feb-81     3
    7521     WARD SALESMAN 7698     22-Feb-81     3
    7654     MARTIN SALESMAN 7698     28-Sep-81     3
    7844     TURNER SALESMAN 7698     8-Sep-81     3
    7900     JAMES CLERK 7698     3-Dec-81     3
    7782     CLARK MANAGER 7839     9-Jun-81     2
    7934     MILLER CLERK 7782     23-Jan-82     3

    Hi,
    user10503747 wrote:
    Hi ,
    please help me in understand connect By Prior
    I did a sample example , but unale to follow , please explain
    How did it understand that KING shuld be displaed first .
    On wht basis the results are shown here ?In a CONNECT BY query (without an ORDER BY clause), if x is an ancestor of y (that is, if x is the parent of y, or x is the parent of the parent of y, and so on), then y will be displayed after x, but before any other row that does not have x as its ancestor. (That is also the order in which ROWNUM will be assigned. This applies only to the query in which CONNECT BY is done. If you use the results set as a sub-query, the super query may cause the results to be re-arranged. An ORDER BY clause always takes precedence.)
    In a CONNECT BY query, every row in the result set either:
    (a) satisfies the START WITH condition, or
    (b) is a descendant of some row in (a); that is, some row that satifies the START WITH condition is its ancestor.
    Since ancestors always come before their descendants, the first row in the result set must be a row that satisfied the START WITH condition. In your example, the row with ename='KING' was the only row that satisfied the condition "START WITH mgr IS NULL", and all the other rows are its descendants, so the row with ename='KING' must come first, as APC said.

  • CONNECT BY PRIOR on 9i

    This 9i SQL Reference indicates that it is possible to combine CONNECT BY PRIOR with a join predicate.
    In 8i I get the following error:
    ORA-01437 cannot have join with CONNECT BY
    Cause: A join operation was specified with a CONNECT BY clause. If a CONNECT BY clause is used in a SELECT statement for a tree-structured query, only one table may be referenced in the query.
    Action: Remove either the CONNECT BY clause or the join operation from the SQL statement.
    I can't find documentation to test the obvious hypothesis - comments?

    My alternative solutions.
    ***Sample***
    ID  PrevID
    1    null
    2       1
    3       1
    4       3
    ***output which we want***
    ID  PrevID  isLeaf
    1    null       0
    2       1       1
    3       1       0
    4       3       1
    ***DDL***
    create table CloneIsLeaf as
    select 1 as ID,null as PrevID from dual
    union select 2,1 from dual
    union select 3,1 from dual
    union select 4,3 from dual;
    --method1
    select ID,PrevID,
    case when exists(select 1 from CloneIsLeaf b
                      where a.ID = b.PrevID) then 0 else 1 end as isLeaf
      from CloneIsLeaf a
    Start With ID = 1
    connect by prior ID = PrevID;
    --method2
    select ID,PrevID,
    case when Level < Lead(Level) over(order by RowNum)
         then 0 else 1 end as isLeaf
      from CloneIsLeaf
    Start With ID = 1
    connect by prior ID = PrevID;
    --method3
    select ID,PrevID,
    case when LV < Lead(LV) over(order by RowNum)
         then 0 else 1 end as isLeaf
    from (select ID,PrevID,Level as LV
            from CloneIsLeaf
          Start With ID = 1
          connect by prior ID = PrevID
          order siblings by ID);
    --method4
    select ID,PrevID,
    case when LV < Lead(LV) over(order by Row_Num)
         then 0 else 1 end as isLeaf
    from (select ID,PrevID,LV,RowNum as Row_Num
            from (select ID,PrevID,Level as LV
                    from CloneIsLeaf
                  Start With ID = 1
                  connect by prior ID = PrevID
                  order siblings by ID));on method2 and method3 and method3,
    I used that "Hierarchical Queries" is depth-first search (http://en.wikipedia.org/wiki/Depth-first_search)
    http://download-west.oracle.com/docs/cd/B19306_01/server.102/b14200/queries003.htm#i2053935
    my site :-)
    http://www.geocities.jp/oraclesqlpuzzle/10-149.html

  • Connect by prior by speific order problem.

    Oracle: 10.2.0.4
    I have a table containing events backup.
    i want to list the hierarchy within that backup oreder by the time_stamp for all levels.
    create table BCK_EVENTS
      bck_backup_id           NUMBER(9) default 0 not null,
      event_id                   NUMBER(15) default 0 not null,
      event_name              NVARCHAR2(100) default ' ' not null
      time_stamp               NUMBER(9) default 0 not null,
      parent_event            NUMBER(15) default 0 not null,
    add constraint BCK_EVENTS_PK primary key (BCK_EVENT_ID, EVENT_ID); // event_id is not unique can be under one or more backup id'sthis is not a tree with one root, there is more than one event in the root level (level 1).
    example:
    Event Name      Time         level   <- time is numeric but for easier reading.
    *Event A          10:00         1
       *Event C        10:30         2
         *Event B      11:17         3
    *Event H          12:10         1
         *Event J       12:10         2
         *Event M      12:21         2
    *Event Z          15:33         1
       *Event R        16:56          2
        *Event M      16:57          3
       *Event G        20:20         2What i tried was :
    select  lpad( '*', level*2 ) || event_id,event_name,time_stamp,parent_event,level from bck_events
         where bck_event_id=100031
         start with parent_event is null
        connect by prior event_id = parent_eventand there are two problems with it.
    1. it's not ordered even when i added an Index (parent_event,time_stamp) and try to hint it.
    2. it returns loads of multiple rows.
    hope it's clear enough. I thank for any help.
    Edited by: 973065 on Nov 25, 2012 8:04 AM
    Edited by: 973065 on Nov 25, 2012 9:23 AM
    Edited by: 973065 on Nov 25, 2012 9:29 AM
    Edited by: 973065 on Nov 25, 2012 9:31 AM

    Hi,
    973065 wrote:
    Oracle: 10.2
    I have a table containing events backup.
    i want to list the hierarchy within that backup oreder by the time_stamp for all levels.
    create table BCK_EVENTS
    bck_backup_id           NUMBER(9) default 0 not null,
    event_id                   NUMBER(15) default 0 not null,
    event_name              NVARCHAR2(100) default ' ' not null
    time_stamp               NUMBER(9) default 0 not null,
    parent_event            NUMBER(15) default 0 not null,
    Thanks for posting the version number and the CREATE TABLE statement. Don't forget to post INSERT statements for your sample data.
    add constraint BCK_EVENTS_PK primary key (BCK_EVENT_ID, EVENT_ID); // event_id is not unique can be under one or more backup id's
    this is not a tree with one root, there is more than one event in the root level (level 1).Is it a forest, that is, a set of trees?
    example:
    Event Name      Time         level   <- time is numeric but for easier reading.
    *Event A          10:00         1
    *Event C        10:30         2
    *Event B      11:17         3
    *Event H          12:10         1
    *Event J       12:10         2
    *Event M      12:21         2
    *Event Z          15:33         1
    *Event R        16:56          2
    *Event M      16:57          3
    *Event G        20:20         2
    That seems to be a forest, that is, every row has 0 or 1 parent, and no row is its own ancestor.
    What i tried was :
    select lpad( '*', level*2 ) || event_id,event_name,time_stamp,parent_event,level from bck_events
    where bck_event_id=100031
    start with parent_event is null
    connect by prior event_id = parent_event
    and there are two problems with it.
    1. it's not ordered even when i added an Index (parent_event,time_stamp) and try to hint it.Depending on your data, you may just need to add
    ORDER SIBLINGS BY  time_stampat the end, after the CONNECT BY clause.
    If you need rows sorted by time_stamp under their roots, but otherwise without regard to the hierarchy, then use CONNECT_BY_ROOT.
    2. it returns loads of multiple rows.Again, it depends on your data. I'll bet you need something more in the CONNECT BY clause, but I can't tell what without some sample data and an exxplanation of how you gett the results you posted from that data. The fact that bck_event_id is part of the primary key makes me suspect that maybe bck_event_id needs to be somewhere in the CONNECT BY clause, but that's just a wild guess.
    hope it's clear enough. I thank for any help.As mentioned before, see the forum FAQ {message:id=9360002}

  • Connect by prior usage restricted to certain level in an hierarchy.

    Hi,
    I had a requirement where the values are stored in a hierarchial basis in a database table. The hierarchy is upto five levels. When I use connect by prior, its using all the five levels to evaluate. But I want to restrict the evaluation upto only three levels. So can anyone help me out in resolving the issue. I would like to know how we restrict, the usage to only say, two or three levels.
    Any help is highly appreciated.
    Thanks and Regards,
    Venky.

    Just add AND LEVEL < 4 to CONNECT BY clause. For example:
    SQL> select lpad(' ',(level-1)*2) || level || ' ' || ename as ename
      2    from emp
      3    start with mgr is null
      4    connect by prior empno = mgr
      5        and level < 4;
    ENAME
    1 KING
      2 JONES
        3 SCOTT
        3 FORD
      2 BLAKE
        3 ALLEN
        3 WARD
        3 MARTIN
        3 TURNER
        3 JAMES
      2 CLARK
    ENAME
        3 MILLER
    12 rows selected.
    SQL> SY.

  • CONNECT BY PRIOR question

    Hi, I have following problem
    Table TMP contains following data
    ID PID
    1
    2 1
    3 2
    select t.id
    from tmp t
    where level=(select max(level)
    from tmp t2
    connect by prior t2.pid=t2.id
    start with t2.id=&ID)
    connect by prior t.pid=t.id
    start with t.id=&ID
    Select returns 1 when ID=3
    Is there a way to write select so that it returns value for first node
    and value of ID used in select?
    Something like
    select value_of_ID
    ,t.id
    from tmp t
    start with t.id=&ID
    so I could use group by on first column (group by value_of_ID)
    Following select would not satisfy:
    select &ID
    ,t.id
    from tmp t
    start with t.id=&ID

    I would suggest something more straightforward:
    select :startnode, id
      from tmp
    where pid is null
    start with id = :startnode
    connect by prior pid = id;The WHERE clause will limit the result to just the top level - no need for a subquery or aggregate functions.

  • Connect by prior query

    Issue with the below query. The query is not getting filtered for the condition hier_typ_c in('BS') with the connect by prior
    query. query is fetching all the hier_type_c in the table like 'BS', 'CO', 'EC' etc....
    Just wondering how do i restrict the query just to fetch the type_c ='BS' alone? why is it giving all the records??
    Select 
            Level                 as  LEVEL_CODE,
            h.HIER_PRNT_NODE_I    as  PARENT,
            h.HIER_CHLD_NODE_I    as  CHILD,
            h.HIER_CHLD_NODE_X || ' (' || h.HIER_CHLD_NODE_I || ')'   as  ALIAS
            From        (Select  Distinct HIER_CHLD_NODE_I, HIER_PRNT_NODE_I,
                                HIER_CHLD_NODE_X from .HIER_DIMN
                         where hier_typ_c in('BS') and CURR_VER_C = 'Y') h
                         Start with  h.HIER_PRNT_NODE_I = 'ROOT'
            Connect by prior
                   h.HIER_CHLD_NODE_I = h.HIER_PRNT_NODE_I
    Order by    LEVEL_CODE, parent, child

    Hi
    It loks like you're doing it right.
    By basing the CONNECT BY query on a sub-query that has this WHERE clasue:
    where hier_typ_c in('BS') and CURR_VER_C = 'Y') hyou should exclude not only nodes whose hier_typ_c is not 'BS', but also their descendants.
    Post some sample data (CREATE TABLE and INSERT statements) and the results you want from that data.
    Are you sure the query you posted is what you're actually running?
    I would expect the sub-query FROM clause to cause an error because of the '.'.
    from .HIER_DIMNEdited by: Frank Kulash on Sep 29, 2009 11:16 AM

Maybe you are looking for

  • Printing custom error Messages in Messages column in WEBADI Excel Template

    I have created a Custom PL/SQL API and Custom integrator to upload data in our Custom Table for Receipts and Payments. Im printing error messages using the RAISE APPLICATION ERROR in the Messages Column of webadi upload spreadsheet. However the error

  • Flash Manual Painter Help

    Hi All, a Help on this will be really appreciated - need a logia something like to paint some Objects: simply put some MCs. When the Mcs (are out of the Box range) and neat its easy to colour. I dont see a place to attach files and I asking for help

  • Memory requirements for query

    Hello, is there some way that i could find out how much memory query will demand to be succesfuly executed ? Maybe to see how much each object referenced in the FROM part of the clause is big ? requirements

  • Why is the Droid Charge the most expensive Verizon smartphone at the moment?

    why is the Droid Charge the most expensive Verizon smartphone at the moment? (currently $299 on the VZW website)

  • Lost audio from after effects to FCP

    I am exporting movies as quick time and going from AE to FCP. In the first two clips I had no issues at all. The second two clips I totally lost my audio. All the clips are from the same footage...same file size etc...why would that happen?