Connect By Prior

Hi Friends,
I have a Query in which i fetch all the child records of parent using connect by prior.But with this i want that it also returns the parent also.
Like If A has three child B,C,D then it returns only B,C,D but with this i want that it also returns the A.
And the finsl result will includes A,B,C,D all values.
There is the Query
SELECT A.ACCOUNT_NUMBER, A.ACCOUNT_ID, A.FUNCTIONAL_CURRENCY_CODE, A.ACCOUNT_NAME, PARENT_ACCOUNT_NUMBER
     FROM
          (SELECT CHILD_ACCOUNT_NUMBER,PARENT_ACCOUNT_NUMBER
          FROM ACCOUNT_MEMBER
                    START WITH     PARENT_ACCOUNT_NUMBER = (SELECT ACCOUNT_NUMBER
                                                                 FROM ACCOUNT
                                                                 WHERE ACCOUNT_ID = '1671'
                    CONNECT BY PRIOR
     CHILD_ACCOUNT_NUMBER = PARENT_ACCOUNT_NUMBER
          )AM,
          ACCOUNT A
WHERE A.ACCOUNT_NUMBER = AM.CHILD_ACCOUNT_NUMBER.
Plz suggest me that how can i fetch the Parent also with the child values.
Neeraj Goel

Hi,
I know nothing of your data structure and can just
interpret your example (it would be helpfull to give
us create table and some data script).
IMHO you need the following
SELECT A.ACCOUNT_NUMBER, A.ACCOUNT_ID, A.FUNCTIONAL_CURRENCY_CODE, A.ACCOUNT_NAME, PARENT_ACCOUNT_NUMBER
FROM
(SELECT CHILD_ACCOUNT_NUMBER,PARENT_ACCOUNT_NUMBER
FROM ACCOUNT_MEMBER
START WITH CHILD_ACCOUNT_NUMBER = (SELECT ACCOUNT_NUMBER
FROM ACCOUNT
WHERE ACCOUNT_ID = '1671'
CONNECT BY PRIOR
CHILD_ACCOUNT_NUMBER = PARENT_ACCOUNT_NUMBER
)AM,
ACCOUNT A
WHERE A.ACCOUNT_NUMBER = AM.CHILD_ACCOUNT_NUMBER
Rgds.

Similar Messages

  • SQL with connect by prior running for a long time

    Hi,
    We are using Oracle 10g. Below is a cursor sql which is having performance issues. The pAccountid is being passed from the output of a different cursor. But this cursor sql is running for a long time. Could you please help me in tuning this sql. I believe the subquery with connect by prior is causing the trouble.
    The TRXNS is a huge table which is not partitioned. The query is forced to use the index on the accountid of the TRXNS table.
    The accountlink table has 20,000 records and the TRXNStrack table has 10,000 records in total.
    This sql executes for 200,000 pAccountids and runs for more than 8 hours.
    SELECT /*+ INDEX(T TRXNS_ACCOUNTID_NIDX) */ AL.FROMACCOUNTID oldaccountid ,
                                    A.ACCOUNTNUM  oldaccountnum,
                                   T.TRXNSID,
                                   T.TRXNSTYPEID,
                                   T.DESCRIPTION ,
                                   T.postdt,
                                   T.TRXNSAMT
                        FROM
                        ACCOUNTLINK AL,
                        TRXNS T,
                        ACCOUNT A
                       WHERE AL.TOACCOUNTID IN
                                                             (SELECT TOACCOUNTID FROM ACCOUNTLINK START WITH TOACCOUNTID = pAccountid
                                                                                                                         CONNECT BY PRIOR FROMACCOUNTID  = TOACCOUNTID)
                            AND AL.FROMACCOUNTID = T.ACCOUNTID
                            AND A.ACCOUNTID = AL.FROMACCOUNTID
    AND NOT EXISTS (select 1 from TRXNStrack trck where trck.TRXNSid = t.TRXNSid AND TRXNSTrackReasonid = 1)
                            AND T.postdt > A.CLOSEDATE
                            AND T.postdt >= sysdate-2
                            AND T.postdt <= sysdate;
    Create script for trxn table:
    CREATE TABLE SP.TRXNS
      TRXNSID      NUMBER(15) CONSTRAINT "BIN$rpIQEeyLDfbgRAAUT4DEnQ==$0" NOT NULL,
      ACCOUNTID    NUMBER(15) CONSTRAINT "BIN$rpIQEeyMDfbgRAAUT4DEnQ==$0" NOT NULL,
      STATEMENTID  NUMBER(15),
      TRXNSTYPEID  NUMBER(15),
      DESCRIPTION  VARCHAR2(80 BYTE),
      postdt     DATE,
      TRXNSAMT     NUMBER(12,2),
      TRXNSREQID   NUMBER(15),
      LASTUPDATE   DATE,
      SOURCEID     NUMBER(15),
      HIDE         VARCHAR2(1 BYTE)
    TABLESPACE SO_TRXN_DATA
    RESULT_CACHE (MODE DEFAULT)
    PCTUSED    40
    PCTFREE    10
    INITRXNS   2
    MAXTRXNS   255
    STORAGE    (
                INITIAL          50M
                NEXT             1M
                MINEXTENTS       1
                MAXEXTENTS       UNLIMITED
                PCTINCREASE      0
                FREELISTS        8
                FREELIST GROUPS  1
                BUFFER_POOL      DEFAULT
                FLASH_CACHE      DEFAULT
                CELL_FLASH_CACHE DEFAULT
    LOGGING
    NOCOMPRESS
    NOCACHE
    NOPARALLEL
    MONITORING;
    CREATE INDEX SP.TRXNS_ACCOUNTID_NIDX ON SP.TRXNS
    (ACCOUNTID, postdt)
    LOGGING
    TABLESPACE SO_TRXN_INDEX
    PCTFREE    10
    INITRXNS   2
    MAXTRXNS   255
    STORAGE    (
                INITIAL          64K
                NEXT             1M
                MINEXTENTS       1
                MAXEXTENTS       UNLIMITED
                PCTINCREASE      0
                FREELISTS        1
                FREELIST GROUPS  1
                BUFFER_POOL      DEFAULT
                FLASH_CACHE      DEFAULT
                CELL_FLASH_CACHE DEFAULT
    NOPARALLEL;
    below is the executing plan for this sql taken from toad :
    PLAN_ID
    TIMESTAMP
    OPERATION
    OPTIONS
    OBJECT_OWNER
    OBJECT_NAME
    OBJECT_ALIAS
    OBJECT_INSTANCE
    OBJECT_TYPE
    OPTIMIZER
    SEARCH_COLUMNS
    ID
    PARENT_ID
    DEPTH
    POSITION
    COST
    CARDINALITY
    BYTES
    CPU_COST
    IO_COST
    TEMP_SPACE
    ACCESS_PREDICATES
    FILTER_PREDICATES
    PROJECTION
    TIME
    QBLOCK_NAME
    1121
    9/10/2013 3:30
    FILTER
    1
    0
    1
    1
    NOT EXISTS (SELECT 0 FROM "TRXNSTRACK" "TRCK" WHERE "TRXNSTRACKREASONID"=1 AND "TRCK"."TRXNSID"=:B1)
    AL."FROMACCOUNTID"[NUMBER,22], "T"."TRXNSID"[NUMBER,22], "T"."TRXNSTYPEID"[NUMBER,22], "T"."DESCRIPTION"[VARCHAR2,80], "T"."POSTDT"[DATE,7], "T"."TRXNSAMT"[NUMBER,22], "A"."ACCOUNTNUM"[VARCHAR2,19]
    SEL$5DA710D3
    1121
    9/10/2013 3:30
    FILTER
    2
    1
    2
    1
    SYSDATE@!-2<=SYSDATE@!
    AL."FROMACCOUNTID"[NUMBER,22], "T"."TRXNSID"[NUMBER,22], "T"."TRXNSTYPEID"[NUMBER,22], "T"."DESCRIPTION"[VARCHAR2,80], "T"."POSTDT"[DATE,7], "T"."TRXNSAMT"[NUMBER,22], "A"."ACCOUNTNUM"[VARCHAR2,19]
    1121
    9/10/2013 3:30
    NESTED LOOPS
    3
    2
    3
    1
    (#keys=0) "AL"."FROMACCOUNTID"[NUMBER,22], "T"."TRXNSID"[NUMBER,22], "T"."TRXNSTYPEID"[NUMBER,22], "T"."DESCRIPTION"[VARCHAR2,80], "T"."POSTDT"[DATE,7], "T"."TRXNSAMT"[NUMBER,22], "A"."ACCOUNTNUM"[VARCHAR2,19]
    1121
    9/10/2013 3:30
    NESTED LOOPS
    4
    3
    4
    1
    5
    1
    119
    3989858
    4
    (#keys=0) "AL"."FROMACCOUNTID"[NUMBER,22], "T"."TRXNSID"[NUMBER,22], "T"."TRXNSTYPEID"[NUMBER,22], "T"."DESCRIPTION"[VARCHAR2,80], "T"."POSTDT"[DATE,7], "T"."TRXNSAMT"[NUMBER,22], "A".ROWID[ROWID,10]
    1
    1121
    9/10/2013 3:30
    NESTED LOOPS
    5
    4
    5
    1
    4
    1
    90
    3989690
    3
    (#keys=0) "AL"."FROMACCOUNTID"[NUMBER,22], "T"."TRXNSID"[NUMBER,22], "T"."TRXNSTYPEID"[NUMBER,22], "T"."DESCRIPTION"[VARCHAR2,80], "T"."POSTDT"[DATE,7], "T"."TRXNSAMT"[NUMBER,22]
    1
    1121
    9/10/2013 3:30
    HASH JOIN
    SEMI
    6
    5
    6
    1
    3
    2
    54
    3989094
    2
    AL."TOACCOUNTID"="TOACCOUNTID"
    (#keys=1) "AL"."FROMACCOUNTID"[NUMBER,22]
    1
    1121
    9/10/2013 3:30
    INDEX
    FULL SCAN
    SP
    ACCOUNTLINK_AK1
    AL@SEL$1
    INDEX (UNIQUE)
    ANALYZED
    7
    6
    7
    1
    1
    18
    252
    107
    1
    AL."FROMACCOUNTID"[NUMBER,22], "AL"."TOACCOUNTID"[NUMBER,22]
    1
    SEL$5DA710D3
    1121
    9/10/2013 3:30
    VIEW
    SYS
    VW_NSO_1
    VW_NSO_1@SEL$5DA710D3
    11
    VIEW
    8
    6
    7
    2
    2
    18
    234
    107
    1
    TOACCOUNTID[NUMBER,22]
    1
    SEL$683B0107
    1121
    9/10/2013 3:30
    CONNECT BY
    NO FILTERING WITH START-WITH
    9
    8
    8
    1
    TOACCOUNTID=PRIOR "FROMACCOUNTID"
    TOACCOUNTID=56354162
    TOACCOUNTID[NUMBER,22], "FROMACCOUNTID"[NUMBER,22], PRIOR NULL[22], LEVEL[4]
    SEL$683B0107
    1121
    9/10/2013 3:30
    INDEX
    FULL SCAN
    SP
    ACCOUNTLINK_AK1
    ACCOUNTLINK@SEL$3
    INDEX (UNIQUE)
    ANALYZED
    10
    9
    9
    1
    1
    18
    252
    107
    1
    ACCOUNTLINK.ROWID[ROWID,10], "FROMACCOUNTID"[NUMBER,22], "TOACCOUNTID"[NUMBER,22]
    1
    SEL$3
    1121
    9/10/2013 3:30
    TABLE ACCESS
    BY INDEX ROWID
    SP
    TRXNS
    T@SEL$1
    2
    TABLE
    ANALYZED
    11
    5
    6
    2
    1
    1
    63
    298
    1
    T."TRXNSID"[NUMBER,22], "T"."TRXNSTYPEID"[NUMBER,22], "T"."DESCRIPTION"[VARCHAR2,80], "T"."POSTDT"[DATE,7], "T"."TRXNSAMT"[NUMBER,22]
    1
    SEL$5DA710D3
    1121
    9/10/2013 3:30
    INDEX
    RANGE SCAN
    SP
    TRXNS_ACCOUNTID_NIDX
    T@SEL$1
    INDEX
    ANALYZED
    2
    12
    11
    7
    1
    1
    1
    224
    1
    AL."FROMACCOUNTID"="T"."ACCOUNTID" AND "T"."POSTDT">=SYSDATE@!-2 AND "T"."POSTDT"<=SYSDATE@!
    T.ROWID[ROWID,10], "T"."POSTDT"[DATE,7]
    1
    SEL$5DA710D3
    1121
    9/10/2013 3:30
    INDEX
    UNIQUE SCAN
    SP
    ACCOUNT_PK
    A@SEL$1
    INDEX (UNIQUE)
    ANALYZED
    1
    13
    4
    5
    2
    1
    1
    90
    1
    A."ACCOUNTID"="AL"."FROMACCOUNTID"
    A.ROWID[ROWID,10]
    1
    SEL$5DA710D3
    1121
    9/10/2013 3:30
    TABLE ACCESS
    BY INDEX ROWID
    SP
    ACCOUNT
    A@SEL$1
    3
    TABLE
    ANALYZED
    14
    3
    4
    2
    1
    1
    29
    168
    1
    A."CLOSEDATE"<SYSDATE@! AND "T"."POSTDT">"A"."CLOSEDATE"
    A."ACCOUNTNUM"[VARCHAR2,19]
    1
    SEL$5DA710D3
    1121
    9/10/2013 3:30
    INDEX
    RANGE SCAN
    SP
    TRXNSTRACK_TRXNSID_NIDX
    TRCK@SEL$6
    INDEX
    ANALYZED
    2
    15
    1
    2
    2
    1
    1
    10
    73
    1
    TRCK."TRXNSID"=:B1 AND "TRXNSTRACKREASONID"=1
    TRCK."TRXNSID"[NUMBER,22], "TRXNSTRACKREASONID"[NUMBER,22]
    1
    SEL$6
    Please help me in debugging this thanks!

    Hi,
    Thanks for your thought on this subject. Below is the trace info that I got from the DBA
    SQL ID: d0x879qx2zgtz Plan Hash: 4036333519
    SELECT /*+ INDEX(T TRXNS_ACCOUNTID_NIDX) */ AL.FROMACCOUNTID OLDACCOUNTID ,
      A.ACCOUNTNUM OLDACCOUNTNUM, T.TRXNSID, T.TRXNSTYPEID, T.DESCRIPTION ,
      T.POSTDT, T.TRXNSAMT
    FROM
    ACCOUNTLINK AL, TRXNS T, ACCOUNT A WHERE AL.TOACCOUNTID IN (SELECT
      TOACCOUNTID FROM ACCOUNTLINK START WITH TOACCOUNTID = :B3 CONNECT BY PRIOR
      FROMACCOUNTID = TOACCOUNTID) AND AL.FROMACCOUNTID = T.ACCOUNTID AND
      A.ACCOUNTID = AL.FROMACCOUNTID AND NOT EXISTS (SELECT 1 FROM TRXNSTRACK
      TRCK WHERE TRCK.TRXNSID = T.TRXNSID AND TRXNSTRACKREASONID = :B4 ) AND
      T.POSTDT > A.CLOSEDATE AND T.POSTDT >= :B2 AND T.POSTDT <= :B1
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        0      0.00       0.00          0          0          0           0
    Execute  17160      2.10       1.87          0          0          0           0
    Fetch    17160   7354.61    7390.86     169408    5569856  883366791           0
    total    34320   7356.71    7392.74     169408    5569856  883366791           0
    Misses in library cache during parse: 0
    Optimizer mode: CHOOSE
    Parsing user id: 38     (recursive depth: 1)
    SQL ID: gs89hpavb4cts Plan Hash: 3415795327
    SELECT A.ACCOUNTID, C.MEMBERID, A.PROGRAMID, A.ACCOUNTNUM
    FROM
    CUSTOMER C, CUSTOMERACCOUNT CA, ACCOUNT A, PROGRAMPARAMVALUE PPV,
      BATCHPROCESSPROGRAM BP WHERE A.PROGRAMID = BP.PROGRAMID AND A.PROGRAMID =
      PPV.PROGRAMID AND A.ACCOUNTID = CA.ACCOUNTID AND CA.PERSONID = C.PERSONID
      AND PPV.PARAMID = :B2 AND PPV.VALUE = 'Y' AND BP.PROCESSID = :B1 AND BP.RUN
      = 'Y' AND A.ACCOUNTTYPEID = 4 AND A.ACCOUNTSTATUSID = 1 AND C.MEMBERID IS
      NOT NULL
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        0      0.00       0.00          0          0          0           0
    Execute      0      0.00       0.00          0          0          0           0
    Fetch      172     13.14     115.34      80826     278650          0       17200
    total      172     13.14     115.34      80826     278650          0       17200
    Misses in library cache during parse: 0
    Parsing user id: 38     (recursive depth: 1)
    OVERALL TOTALS FOR ALL NON-RECURSIVE STATEMENTS
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        0      0.00       0.00          0          0          0           0
    Execute      0      0.00       0.00          0          0          0           0
    Fetch        0      0.00       0.00          0          0          0           0
    total        0      0.00       0.00          0          0          0           0
    Misses in library cache during parse: 0
    OVERALL TOTALS FOR ALL RECURSIVE STATEMENTS
    call     count       cpu    elapsed       disk      query    current        rows
    Parse        0      0.00       0.00          0          0          0           0
    Execute  17160      2.10       1.87          0          0          0           0
    Fetch    17332   7367.75    7506.21     250234    5848506  883366791       17200
    total    34492   7369.85    7508.09     250234    5848506  883366791       17200
    Misses in library cache during parse: 0
        2  user  SQL statements in session.
        0  internal SQL statements in session.
        2  SQL statements in session.
    Trace file: svoprod_ora_12346.trc
    Trace file compatibility: 11.1.0.7
    Sort options: default
           1  session in tracefile.
           2  user  SQL statements in trace file.
           0  internal SQL statements in trace file.
           2  SQL statements in trace file.
           2  unique SQL statements in trace file.
       66499  lines in trace file.
        7516  elapsed seconds in trace file.

  • Connect by Prior in Oracle 8i question

    Need help with building tree-structured query in Oracle 8i (Forms 6i front end if it matters).
    Sample structure and data:
    CREATE TABLE table_list
    my_code NUMBER,
    my_level NUMBER,
    my_description VARCHAR2(60)
    CREATE TABLE table_content
    my_code NUMBER,
    term_code NUMBER,
    term_category VARCHAR2(5)
    INSERT into table_list values (101, 1, 'building');
    INSERT into table_list values (102, 2, 'flat');
    INSERT into table_list values (103, 3, 'living room');
    INSERT into table_list values (104, 3, 'bedroom');
    INSERT into table_list values (105, 3, 'bathroom');
    commit;
    INSERT into table_content values (101, 102, 'Sub');
    INSERT into table_content values (102, 103, 'Sub');
    INSERT into table_content values (102, 104, 'Sub');
    INSERT into table_content values (102, 105, 'Sub');
    commit;
    Need to display data in the following order:
    101 'building' --level one
         102 'flat' --level two
              105 'bathroom' --level three
              104 'bedroom' --level three
              103 'living room' --level three
    *(note alphabetical order in level three)*
    Looks like Oracle 8i does not support table joins for CONNECT BY PRIOR. Please advise!

    And you are correct, it does not display level 1. Do
    you think this is this a database structure problem
    or it could be corrected via query modification?No and yes. It's not a "structure" problem, its a data problem (as I explained above). You always fix data problems by making queries overly complex (hint, hint, I don't suggest doing it this way).
    select tl.my_level, tl.my_description , LPAD(' ',3*(my_level-1)) || substr(tl.my_description, 1, 30) description
    from table_list tl,
    (select term_Code from table_content
    start with my_code in (select my_code from table_list where my_level=1)
    connect by prior term_code = my_code
    ) x
    where x.term_code = tl.my_code
    union all
    select my_level, my_description
    from table_list
    where my_level = 1
    order by 1, 2
    better to add a row to table_content with my_code=null, term_code=101.
    otherwise you'll be pulling stupid nonsense like above with every query from here on out.

  • How to use simple SQL instead of Connect By Prior

    Currently, I am using "connect by prior" query in the application, but for reason I don�t want to use this connect by query so can any one please tell how does I get the same result by using SQL, I tried this by using procedure but unable to get the same result, specially LEVEL of the tree.
    So please tell, how would I get the correct data.
    Thanks in advance,
    AMIT.

    Hi,
    Whenever you have a question, it helps to post:
    (1) The version of Oracle (and any other relevant software) you're using
    (2) A little sample data (just enough to show what the problem is) from all the relevant tables
    (3) The results you want from that data
    (4) Your best attempt so far (formatted) I don't believe the unformated code you posted is what you're really running, since it has a syntax error ("... WHERE START WITH ..."). Please post code that really works with the sample data you posrted.
    (5) The full error message (if any), including line number
    Executable SQL statements (like "CREATE TABLE AS ..." or "INSERT ..." statements) are best for (2).
    If you can present your problem using commonly available tables (for example, scott.emp, which contains a hierarchy), then you can omit (2).
    Formatted tabular output is okay for (3). Type these 6 characters
    &#123;code&#125;
    (small letters only, inside curly brackets) before and after the tabular text, to preserve spacing.
    As Alex said, why don't you want to use CONNECT BY?
    Are you getting the correct results now, but just looking for a different way of getting them?
    Depending on your exact requirements, you could write a PLSQL function that mimics LEVEL. Don't expect it to be fast.
    Nested Sets is a completely different way of modeling trees.
    Some things are much easier with Nested Sets than they are using the Adjacency Model (the parent-child model that uses CONNECT BY).
    But some things are much harder with Nested Sets, and LEVEL is one of them.

  • How to get the root node for a child using connect by prior

    Hi,
    I searched at many places to do this but not able to get the exact o/p sp posting my question here.
    I have a table with parent_id and child_id columns. The levels of this parent_child can be many but my aim is to find the ultimate parent ( dont know the right term)
    like if I have a child_node= xyz and its parent= pqr and its parents=lmn which might be ultimate parent which doesnt have any further parent.
    So if i start with child_code= "xyz" then i should get the parent as "lmn" and not the immediate parent "pqr".
    Please help.
    Thanks,
    Aashish

    To find the Parent on emp table:
    select empno,ename,level
    from emp
    where level=3
    start with empno=7934
    connect by  empno= prior mgrTo find the Child on emp table:
    select empno,ename,level
    from emp
    where level=1
    start with empno=7934
    connect by prior empno=  mgrBut you need to know the level or position to specify the level of parent or child. But there are some other possible options available if we can know the requirement properly.
    Edited by: Vasista on Jan 11, 2011 2:27 AM
    Edited by: Vasista on Jan 11, 2011 2:30 AM

  • Query tuning for query using connect by prior

    I have written following query to fetch the data. The query is written in this format because there are multiple rows, which make one recrd and we need to bring that record into one row.
    For one CAT(commented here), this query takes around 4 minutes and fetches 6900 records but when it runs for 3 CAT, it takes 17 mins.
    I want to tune this as this has to run for 350 CAT values.
    It is doing FTS on the main table. I tried to use different hints like PARALLEL, APPEND (in insert) but nothing worked.
    The cost of the query is 51.
    Any help/suggestions will be appreciated.
    SELECT DISTINCT MIN(SEQ) SEQ,
    PT, APP, IT, LR, QT,CD, M_A_FLAG,
    STRAGG(REM) REM, -- aggregates the data from different columns to one which is parent
    CAT
    FROM (WITH R AS (SELECT CAT, SEQ, PT, M_A_FLAG, IT, LR,QT,CD, REM, APP
    FROM table1
    WHERE REC = '36' AND M_A_FLAG = '1'
    --AND CAT = '11113')
    SELECT CAT, SEQ,
    CONNECT_BY_ROOT PT AS PT,
    CONNECT_BY_ROOT APP AS APPL,
    M_A_FLAG,
    CONNECT_BY_ROOT IT AS IT,
    CONNECT_BY_ROOT LR AS LR,
    CONNECT_BY_ROOT QT AS QT,
    CONNECT_BY_ROOT CD AS CD,
    REM
    FROM R A
    START WITH PT IS NOT NULL
    CONNECT BY PRIOR SEQ + 1 = SEQ
    AND PRIOR CAT = CAT
    AND PT IS NULL)
    GROUP BY PT, APP, IT,LR, QT, CD, M_A_FLAG, CAT
    ORDER BY SEQ;
    Thanks.
    Edited by: user2544469 on Feb 11, 2011 1:12 AM

    The following threads detail the approach and information required.
    Please gather relevant info and post back.
    How to post a SQL tuning request - HOW TO: Post a SQL statement tuning request - template posting
    When your query takes too long - When your query takes too long ...

  • Connect by prior in Oracle 11g

    I am upgrading an application from 9i to 11g and I've been told that the connect by prior sql is broken. While I am waiting for the example and the error message, is 11g pickier about looping than 9i was? Can someone point me to some documentation on 10 or 11 changes to hierarchical queries?
    Thanks in advance.
    Jim

    Hi, Jim,
    user509659 wrote:
    I am upgrading an application from 9i to 11g and I've been told that the connect by prior sql is broken. What do you mean? Post a link, or at least a more complete description of the problem.
    While I am waiting for the example and the error message, is 11g pickier about looping than 9i was? Can someone point me to some documentation on 10 or 11 changes to hierarchical queries?There were a lot of improvements to CONNECT BY in Oracle 10, including CONNECT BY NOCYCLE (for working with loops), the CONNECT_BY_ROOT operator, and pseudo-columns CONNECT_BY_ISCYCLE and CONNECT_BY_ISLEAF. Look them up in the SQL Language manual for your version.
    I don't know of any improvements or changes to CONNECT BY in Oracle 11.
    Oracle 11.2 has recursive WITH clauses, that can do everything that CONNECT BY does, and more. Some things in 11.2 are simpler and more efficient using CONNECT BY, others are better done using recursive WITH clauses.
    Everything that CONNECT BY did in earlier versions, it does in Oracle 11, as well. If you have a CONNECT BY query that works in Oracle 9, it should work in Oracle 11, without any changes, though there might be better ways to get the same results in Oracle 11.
    Whenever you have a question, post youir code, and whatever is necessary to run it, including CREATE TABLE and INSERT statments for a little sample data. Post the results you want from that sample data, and an explanation of how you get those results from that data.
    Always say which version of Oracle you're using, e.g. 11.2.0.2.0. The difference between 11.1 and 11.2 may be very significant in this case.
    See the forum FAQ {message:id=9360002}

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

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

    Hi all,
    In Connect By Prior, How can i avoid, if some parent dont have child means, it should not come in the results.......
    Regards,
    Fame

    A "parent" without a child will not show up as a parent, but it may show up as a child.
    When that happens, CONNECT_BY_ISLEAF will be 1.
    So, filter on CONNECT_BY_ISLEAF = 0.select empno, ename, job, mgr from scott.emp
    where connect_by_isleaf = 0
    start with mgr is null
    connect by mgr = prior empno;
         EMPNO ENAME      JOB              MGR
          7839 KING       PRESIDENT           
          7566 JONES      MANAGER         7839
          7788 SCOTT      ANALYST         7566
          7902 FORD       ANALYST         7566
          7698 BLAKE      MANAGER         7839
          7782 CLARK      MANAGER         7839Edited by: Stew Ashton on Jan 17, 2013 1:34 PM

  • Connect by prior problem with order by

    Hi,
    I and using connect by prior within a query on Oracle 8 and would like to order the results within the parent levels.
    All the documentation that I have read shows that in Oracle 9i there is an option to say order siblings by which looks like what I need, but this does not work on Oracle 8.
    Can anyone tell me how I can order the children within the parents without changing the tree structure?
    I have also tried SYS_CONNECT_BY_PATH and I just get an error saying that it is an invalid column name,

    Karen, see here for a dicussion on how to order the siblings in a pre-9i environment:
    http://asktom.oracle.com/pls/ask/f?p=4950:8:::::F4950_P8_DISPLAYID:9212348049

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

    In our application, we have a lot of 'trees' in our data (parent/child relationships within a table). We rely heavily on 'connect by prior' to search through the trees, to find for example values that are defined in one of the parents ('inheritance').
    Lately however, we've been eliminating connect by priors wherever we can lately, because performance is dramatic. No matter what indexes we use, we keep getting full tablescans on large tables because of the connect by priors. Views with 2 connect by priors are deadly for performance.
    What is a good way to optimize connect by priors?
    As an example of why we use connect by prior, consider this:
    table A
    ID   PARENT_ID   NAME    LENGTH
    1    NULL        root    10
    2    1           child   NULLWe consider record 2 'derived' from record 1, inheriting its length. The alternative for connect by prior is to populate the child length whenever the master length changes, and this is what we do in most situations now, but it's hell to keep track of this. If a record changes, you would still have to go down the tree to change all child lengths etc, so we rather use connect by prior.
    Any ideas?

    Ivo, would you please post the table definition (if different than your example), the actual list of indexes, a sample query, and the explain plan for that query?
    I use hierarchical queries extensively on tables with millions of rows. They work very well if all the pieces are in place. Let's see if we can get your queries humming...

  • 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 statement issue

    Hi,
    I'm using the below select query to build a relationship b/w ID & parent_id, but HANA studio is throwing a syntax error. I don't see a problem around the syntax. Please throw some light's here.
    SELECT * FROM "SIVA_TEST"."Core_Competency" START with  "Competency_ID"=1
    CONNECT BY PRIOR "Competency_ID" = "Parent_Competency_ID"   ;
    Error:
    Could not execute 'SELECT * FROM "SIVA_TEST"."Core_Competency" START WITH "Competency_ID"='1' CONNECT BY PRIOR ...' in 170 ms 563 µs .
    SAP DBTech JDBC: [257] (at 46): sql syntax error: incorrect syntax near "START": line 2 col 1 (at pos 46)
    Table struct:
    create column table "SIVA_TEST"."Core_Competency"("Competency_ID" integer,
    "Competency_Name" varchar(200),
    "Competency_description" varchar(1000),
    "Parent_Competency_ID" integer,
    "start_date" date,
    primary key("Competency_ID"));
    Thanks,
    Siva.

    Insert statement for the corresponding table..
    INSERT INTO "SIVA_TEST"."Core_Competency" VALUES (1,'value 1',null,null,'2013-12-02');
    INSERT INTO "SIVA_TEST"."Core_Competency" VALUES (2,'value 2',null,1,'2013-07-31');
    INSERT INTO "SIVA_TEST"."Core_Competency" VALUES (3,'value 3',null,1,'2013-02-01');
    INSERT INTO "SIVA_TEST"."Core_Competency" VALUES (4,'value 4',null,2,'2013-06-24');
    INSERT INTO "SIVA_TEST"."Core_Competency" VALUES (5,'value 6',null,2,'2013-04-09');
    INSERT INTO "SIVA_TEST"."Core_Competency" VALUES (6,'value 7',null,3,'2013-09-12');
    INSERT INTO "SIVA_TEST"."Core_Competency" VALUES (7,'value 8',null,3,'2013-08-09');
    INSERT INTO "SIVA_TEST"."Core_Competency" VALUES (8,'value 9',null,7,'2013-04-09');
    INSERT INTO "SIVA_TEST"."Core_Competency" VALUES (9,'value 10',null,7,'2013-12-09');
    INSERT INTO "SIVA_TEST"."Core_Competency" VALUES (10,'value 11',null,4,'2013-09-08');
    INSERT INTO "SIVA_TEST"."Core_Competency" VALUES (11,'value 12',null,4,'2013-10-10');

  • Connect by Prior - ORA-00600: internal error code, arguments: [kkqcbydrv:1

    Hi,
    We are writing some complex query using Connect by Prior in it.
    When we execute this query on same version of database as that of our client, then the query is executing.
    But when we execute this query at client's side then it raises error -
    ORA-00600: internal error code, arguments: [kkqcbydrv:1] , [] , [] , [] , [] , [] , [] , []
    After searching on metalink,
    We could find two workarounds -
    1. Use a /*+no_unnest*/ hint, but this may have perfomance implications.
    2. alter session set "_optimizer_connect_by_cost_based"=false;
    of which we cant use second workaround as this query is called from a application and not directly from oracle prompt.
    We are working with the first workaround, but what is wondering us is that,
    If same query can work well on our side then why is this query not performing in same way at client's side?
    We are using same version of database, same amount of data is present in development and production databases.
    Then what is causing this error only in priduction?
    Any help in this regard is appreciated.
    Thanks,
    Av.

    You can use the second tip in a database login trigger. But if the metalink ORA-600 diagnostic tool can only give you those workarounds I suggest raising a SR to try and get the bug fixed.
    It may be differing patch levels that cause the difference between the two sites, some subtle difference in temp tablespace, a corrupt block - impossible for us to say but maybe not for Oracle.

Maybe you are looking for

  • Some D800 Raw files not previewing

    Not sure what the problem is, but every so often, I'll have some D800 Raw files (14 bit, lossless compressed), and the .NEF logo will appear sideways in the preview panel. I can only see the image if I open it up in camera raw or Photoshop. Not sure

  • Workflow not getting triggered from Action definition in CRMD_ORDER

    Hello Experts, I have created a workflow which should send mail to partner team in a Change Request.This workflow should be triggered when a particular Zaction is performed on the CR.Zaction is created properly and my workflow is also assigned to it.

  • ITunes Music Download Issues - Purchased Music Not Displaying in iTunes

    I am having trouble with iTunes. This is what the problem is: 1) Purchased music / TV from iTunes. 2) Paused downloads. 3) Closed iTunes. 4) Later re-opened iTunes 5) Went to Store > Downloads When I do this, the media which I have purchased, but not

  • Remove nodes XML

    Hello, I have this XML "C:\entrega.xml" and I want to remove two nodes. HOW????   <?xml version="1.0" encoding="UTF-16" ?> -<BOM> --<BO> <AdmInfo> <Object>15</Object> <Version>2</Version> <Document_Lines> <row> <BaseType>17</BaseType> <BaseEntry>27</

  • My iphone 3gs brings error message 1602 when trying to restore

    My iphone 3gs brings error message 1602 when trying to restore factory default