CONNECT BY PRIOR - ORDERING ROWS
Hi all,
I am working on database server - oracle 10g enterprise edition R2,
forms - Oracle forms 10G -Version 10.1.2.0.2 on windows 2000 professional.
I have a table ACCOUNT_GROUP_MASTER with the following structure.
DESC ACCOUNT_GROUP_MASTER
Name Null? Type
ACCOUNT_GROUP_CODE NOT NULL NCHAR(6)
ACCOUNT_GROUP_NAME NOT NULL NVARCHAR2(40)
ACCOUNT_GROUP_TYPE CHAR(1)
GROUP_DISP_ORDER NUMBER(3)
MAIN_GROUP_CODE NCHAR(6)
Account_group_code is the primary key
and Main_group_code is the foreign key(self referencing) referring Account_group_code of the same table.
My query and the returned data are given below.
SELECT
level, account_group_code act, GROUP_DISP_ORDER ord
FROM ACCOUNT_GROUP_MASTER
CONNECT BY PRIOR ACCOUNT_GROUP_CODE=MAIN_GROUP_CODE
START WITH main_GROUP_code is null
order by account_group_code
LEVEL ACT ORD
1 4000 1
2 4100
2 4200 3
2 4300 1
1 2000 2
2 2100 2
2 2200 1
My task is to sort the output in the order of
First sort column is "level" and within the "level", data should be sorted by the
group_disp_order column.
That is the above output should come as given below.
LEVEL ACT ORD
1 4000 1
2 4100
2 4300 1
2 4200 3
1 2000 2
2 2200 1
2 2100 2
Can anybody help me please.
Thanks in advance.
Regards
Mohan
Hi All
The solution to the above problem is solved by the following query.
SELECT 1,level, account_group_code|| account_group_NAME,NULL,
account_group_code
FROM ACCOUNT_GROUP_MASTER
CONNECT BY PRIOR ACCOUNT_GROUP_CODE=MAIN_GROUP_CODE
START WITH main_GROUP_code is null
order siblings by group_disp_order
Regards
Mohan
Similar Messages
-
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 AMHi,
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 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 return unnecessary rows
Hello,
I am using oracle 9.2
my query looks like this:
SELECT *
FROM book_items t
where cust_id = 2305240
and sort_key is not null
CONNECT BY PRIOR item_id = parent_id
START WITH t.item_id = 193
ORDER SIBLINGS BY sort_key
the problem is, when I have a father that has no sort_key (null) then it doesn't come up in the result, BUT his child does! they have a sort key, but why do I see them if the father is not exist in the result, it makes no sense to me...?
How can I fix this, if the father doesn't comes up, I don't need his child's?
Thanks.It's documented behaviour that:
Oracle processes hierarchical queries as follows:
A join, if present, is evaluated first, whether the join is specified in the FROM clause or with WHERE clause predicates.
The CONNECT BY condition is evaluated.
Any remaining WHERE clause predicates are evaluated.The predicates "cust_id = 2305240 and sort_key is not null" are applied last. -
Connect by prior - reverse order
Is this possible:
emp - manager
a 0
b a
c a
d b
I can start with the manager = 0 and get the entire tree. I want to start with emp = c and get the tree going the other way .. reverse order. Is this possible ?Do you mean:
SQL> SELECT * FROM t[
EMP MGR
a 0
b a
c a
d b
SQL> SELECT LPAD(' ',2*(LEVEL-1))||emp emp, mgr
2 FROM t
3 START WITH emp = 'c'
4 CONNECT BY PRIOR mgr = emp;
EMP MGR
c a
a 0TTFN
John -
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. -
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 AMThe 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 ... -
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 3Hi,
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 subquery - performance problem
Hello,
I have some data which is organized in a folder tree. The requeriement is to be able to search from any subfolder and down.
/Documents
___Folder A
______Doc A
______Doc B
___Folder B
______Doc C
______Doc D
The folder structure is defined in a table called CORNERS where the records(=folders) has a ID/PARENTID relationsship to describe the folder structure.
Another table, called MASTER, contains the main content. Each item has a CORNERID value which defined in which subfolder the document is located.
MASTER
ID CORNERID TITLE INDEX_URL
100 2 Doc A http://xxx/yy.com
101 2 Doc B http://xxz/yy.com
102 3 Doc C http://xyz/yy.com
103 3 Doc D http://xyz/zz.com
CORNERS
ID PARENTID NAME
1 Documents
2 1 Folder A
3 1 Folder B
MASTER table has ~50000 records
CORNERS has ~900 records.
Analyzed nighly and stats are fresh.
Indexes defined:
CORNERS_ID_PARENT_IDX corners(id,parentid)
CORNERS_PARENT_ID_IDX corners(parentid,id)
MASTER_ID_CORNERID_IDX master(id,cornerid)
MASTER_CORNERID_ID_IDX master(cornerid,id)
Oracle Text index (URL based) on MASTER.INDEX_URL
Foreign key defined:
MASTER.CORNERID references CORNERS.ID
If I do a search without involving the hierarchy, then the search runs pretty fast:
SQL> SELECT COUNT(*) FROM (SELECT a.id, a.cornerid FROM MASTER a WHERE (CONTAINS(title,'$ADS AND {S} AND $PARAMETER',2) > 1 OR CONTAINS(index_url,'$ADS AND {S} AND $PARAMETER',1) > 1) );
COUNT(*)
5125
Elapsed: 00:00:00.14
Execution Plan
0 SELECT STATEMENT Optimizer=CHOOSE (Cost=1354 Card=1 Bytes=15
8)
1 0 SORT (AGGREGATE)
2 1 TABLE ACCESS (BY INDEX ROWID) OF 'MASTER' (Cost=1354 Car
d=758 Bytes=119764)
3 2 BITMAP CONVERSION (TO ROWIDS)
4 3 BITMAP OR
5 4 BITMAP CONVERSION (FROM ROWIDS)
6 5 SORT (ORDER BY)
7 6 DOMAIN INDEX OF 'MASTER_TITLE_IDX' (Cost=470)
8 4 BITMAP CONVERSION (FROM ROWIDS)
9 8 SORT (ORDER BY)
10 9 DOMAIN INDEX OF 'MASTER_IDX' (Cost=650)
Statistics
1462 recursive calls
0 db block gets
5507 consistent gets
347 physical reads
0 redo size
380 bytes sent via SQL*Net to client
503 bytes received via SQL*Net from client
2 SQL*Net roundtrips to/from client
2 sorts (memory)
0 sorts (disk)
1 rows processed
SQL>
BUT, if I add a subquery to limit the search to a certain folder tree (which includes ~200 nodes), then the performance is really badly affected. The subquery itself runs fast - around 0.07 seconds, but together with the rest of the query the preformance is really bad:
SQL> SELECT COUNT(*) FROM (SELECT a.id, a.cornerid FROM MASTER a WHERE (CONTAINS(title,'$ADS AND {S} AND $PARAMETER',2) > 1 OR CONTAINS(index_url,'$ADS AND {S} AND $PARAMETER',1) > 1) AND cornerid IN ( SELECT ID FROM corners START WITH id = 2434 CONNECT BY PRIOR id = parentid) );
COUNT(*)
942
Elapsed: 00:00:01.83
Execution Plan
0 SELECT STATEMENT Optimizer=CHOOSE (Cost=118 Card=1 Bytes=175
1 0 SORT (AGGREGATE)
2 1 TABLE ACCESS (BY INDEX ROWID) OF 'MASTER' (Cost=19 Card=
1 Bytes=162)
3 2 NESTED LOOPS (Cost=118 Card=8 Bytes=1400)
4 3 VIEW OF 'VW_NSO_1' (Cost=2 Card=6 Bytes=78)
5 4 SORT (UNIQUE)
6 5 CONNECT BY (WITH FILTERING)
7 6 NESTED LOOPS
8 7 INDEX (UNIQUE SCAN) OF 'SYS_C002969' (UNIQUE
) (Cost=1 Card=1 Bytes=4)
9 7 TABLE ACCESS (BY USER ROWID) OF 'CORNERS'
10 6 NESTED LOOPS
11 10 BUFFER (SORT)
12 11 CONNECT BY PUMP
13 10 INDEX (RANGE SCAN) OF 'CORNERS_PARENT_ID_IDX
' (NON-UNIQUE) (Cost=2 Card=6 Bytes=48)
14 3 INDEX (RANGE SCAN) OF 'MASTER_CORNERID_ID_IDX' (NON-
UNIQUE) (Cost=1 Card=38)
Statistics
29267 recursive calls
0 db block gets
55414 consistent gets
140 physical reads
0 redo size
380 bytes sent via SQL*Net to client
503 bytes received via SQL*Net from client
2 SQL*Net roundtrips to/from client
12 sorts (memory)
0 sorts (disk)
1 rows processed
I've tried an alternative syntax, instead of the IN clause like this:
SELECT COUNT(*) FROM (
WITH folders AS (
SELECT ID
FROM CORNERS
START WITH ID=2434
CONNECT BY PRIOR ID= PARENTID
SELECT a.id
FROM MASTER a, folders b
WHERE a.cornerid = b.id
AND CONTAINS(index_url,'$ADS AND {S} AND $PARAMETER',1) > 1);
It does runfaster, but still takes around 1 second.
Any suggestion on how to make this run faster!?
Thanks in advance!
-Matshow long does it takes to complete the query?
-
Connect by prior (hierarchical query)
Hi All,
Some1 asked me a question which goes like this:
Source
emp_no dep_no
110 10
110 20
110 30
110 40
120 10
130 10
130 20
write a query to achieve the following output from the above source
emp_no dept_no
110 10203040
120 10
130 1020
Now I have come across solutions with 'connect by prior' clauses but I am nt able to understand how oracle is producing that result , Could someone point me to a good article or text that can explain this concept very thoroughly( I have searched on google and got to see many articles but I couldnt able to understand it since these articles were not explaining everything)
Regards
RahulYou can try this:
SQL> ed
Wrote file afiedt.buf
1 SELECT deptno,MAX(TRIM(SUBSTR(SYS_CONNECT_BY_PATH(empid,','),2)))
2 KEEP(DENSE_RANK LAST ORDER BY deptno) FROM
3 (SELECT deptno,empid,ROW_NUMBER() OVER(PARTITION BY deptno ORDER BY deptno) curr,
4 ROW_NUMBER() OVER(PARTITION BY deptno ORDER BY deptno) - 1 prev
5 FROM emp)
6 CONNECT BY PRIOR curr = prev
7 AND deptno = PRIOR deptno
8 START WITH curr = 1
9* group by deptno
SQL> /
DEPTNO MAX(TRIM(SUBSTR(SYS_CONNECT_BY_PATH(EMPID,','),2)))KEEP(DENSE_RANKLASTORDERBYDEPTNO)
10 1,2,3,4
20 5,6,7
SQL> select deptno,empid from emp;
DEPTNO EMPID
10 1
10 2
10 3
10 4
20 5
20 6
20 7
7 rows selected.
SQL> -
Connect by prior with the hint index not improving the performance
Hi
I have a table ORDERS (transaction table) with a parent order and multiple child orders with a field called orig_tid which track it back to main order.Child order can be further amended it will have mapping to immediate parent and immediate parent will have mapping to its parent.
I want find out al the order associated with main order using connect by prior.
I have created an index on required fileds but still those are not reducing the bytes. It is foing full index scan which are involving big bytes.
[code]
create index idx_test on orders decode(length(nvl(orig_tid,0)),9,substr(tran_no,6),orig_tid)
SELECT /*+ (mmd IDX_TEST) */ *
FROM ORDERS mmd
connect by prior tid=decode(length(nvl(orig_tid,0)),9,substr(tran_no,6),orig_tid)
start_with or_number='13454566654553'
[/CODE]
Explain Plan
ID | OPERATION | NAME | ROWS | BYTES | COST
0 | SELECT STATEMENT | | 9768 | 5093K | 6944
1|CONNECT BY WITH FILTERING| | | |
2|TABLE ACCESS BY INDEX ROWID|ORDERS | 1 |534| 319K
3| INDEX FULL SCAN| IDX_TEST| 976K| | 5652
4|NESTED LOOPS| | | |
5|CONNECT By PUMP | | | |
6| TABLE ACCESS BY INDEX ROWID| ORDERS| 9768 | 5093K| 6944
7| INDEX FULL SCAN | IDX_TEST | 3907| | 5689
Message was edited by: NikhilJunejapost EXPLAIN PLAN for SQL
-
Need help: CONNECT by PRIOR query in ora10g
Hi All,
Recently we have migrated the DB from 9i to 10g.
we used to have many rule based queries in 9i
and all are changed based on 10g.
All the queries that have CONNECT BY PRIOR
conditions seems to behave in wrong manner.
( same query in 9i,fetches less number of records where as 10g there were many
rows displayed eventhough it was not selected in where clause.- as per business logic )
After changing the below parameter setting , the problem was solved.
can you tell wts the below setting would do? by doing so , ur again making 10g
to behave like 9i so that full benefit of 10g is not used ?
Alter session set “_optimizer_connect_by_cost_based”=falseHi, try this:
WITH t AS (
SELECT 100 AS node_id, cast(NULL AS NUMBER) AS parent_node_id FROM dual UNION ALL
SELECT 101 AS node_id, 100 AS parent_node_id FROM dual UNION ALL
SELECT 102 AS node_id, 100 AS parent_node_id FROM dual UNION ALL
SELECT 1021 AS node_id, 102 AS parent_node_id FROM dual UNION ALL
SELECT 1022 AS node_id, 102 AS parent_node_id FROM dual UNION ALL
SELECT 10221 AS node_id, 1022 AS parent_node_id FROM dual UNION ALL
SELECT 10222 AS node_id, 1022 AS parent_node_id FROM dual
SELECT DISTINCT CONNECT_BY_ROOT parent_node_id AS ID, node_id AS id1
FROM t
CONNECT BY t.node_id = PRIOR parent_node_id
START WITH parent_node_id = 1022
ORDER BY 1, 2; -
Complex connect by prior query
I need SQL(for hierarchical tree) for a function which accepts node as input parameter and returns ref cursor.
Following is a sample tree:
1
--2.1
----3.1
------4.1
--------5.1
----------6.1
----------6.2
----3.2
------4.2
--------5.2
--2.2
----3.2
------4.2
--------5.2
----3.3
----3.4
------4.1
--------5.1
----------6.1
----------6.2
1 is at the root level and 2.1 & 2.2 are immediate children and so on.
The output tree should be all related parents and children of the passed node.
e.g:
If the input is 4.1, the output tree will be:
1
--2.1
----3.1
------4.1
--------5.1
----------6.1
----------6.2
--2.2
----3.4
------4.1
--------5.1
----------6.1
----------6.2
If the input is 4.2, the output tree will be:
1
--2.1
----3.2
------4.2
--------5.2
--2.2
----3.2
------4.2
--------5.2
The complex part, I guess, is to remove unwanted(not related) branches from the tree.
Following is the representation of the table RELATIONSHIP
ID PARENT CHILD
1-------1-------2.1
2-------1-------2.2
3-------2.1-----3.1
4-------2.1-----3.2
5-------2.2-----3.2
6-------2.2-----3.3
7-------2.2-----3.4
8-------3.1-----4.1
9-------3.2-----4.2
10------3.4-----4.1
11------4.1-----5.1
12------4.2-----5.2
13------5.1-----6.1
14------5.1-----6.2
Pls. help me out to form this CONNECT BY PRIOR query.
Thanks in advance.make sure you include 2 things in your queries.
# the row number
# the level
for traversing up the tree set
level = 0 - level and
row_number = 0 - row_number.
you than can then do an order by row_number if you union the two queries
for example:
============
select tbl.child,
tbl.parent,
level lvl,
rownum rn
from some_table tbl
start with tbl.parent = 4.1
connect by prior tbl.child = tbl.parent
union
select tbl.child,
tbl.parent,
0 - level lvl,
0 - rownum rn
from some_table tbl
start with tbl.child = 4.1
connect by prior tbl.parent = tbl.child
order by rn asc -
Connect By Prior - Performance and Missing Parent
I have to say right off the top that I'm not a SQL expert by any means so please be gentle. :)
I have a query that runs through a Bill Of Materials that works except for two things:
1. It is horribly slow - 60-90 seconds to return under 300 rows.
2. It doesn't show the parent node.
I'm looking into indexes now, so I'm not sure if there's an issue there or not. As far as #2 goes, there are two tables that are involved: BOM_STRUCTURES_B and BOM_COMPONENTS_B. Every item below the parent node has a BOM_COMPONENTS_B record. If a BOM_COMPONENT is a parent to other components, there is a BOM_STRUCTURES_B record for that. (In other words, everything that is a parent has a BOM_STRUCTURES_B record, and all the children have a BOM_COMPONENTS_B record that point to the parent - BOM_STRUCTURES_B). The only exception to this is the parent node, which only has a BOM_STRUCTURES_B record (it is NOT a child, so there is no BOM_COMPONENTS_B record). I've added a "UNION" to the bottom of the script below, but it changes my sort order completely.
Here's my script:
select bbm.assembly_item_id,
bic.component_item_id Component ,
msi.segment1 Name,
msi.description Description,
bic.component_quantity Quantity,
lpad( ' ', level*2 ) || level MyLevel
from bom_structures_b bbm
,bom_components_b bic
, mtl_system_items msi
where bbm.bill_Sequence_id = bic.bill_sequence_id
and msi.inventory_item_id = bic.component_item_id
and msi.organization_id = bbm.organization_id
start with bbm.assembly_item_id = 271962
and bbm.organization_id = 85
connect by prior bic.component_item_id = bbm.assembly_item_id;
I've hard-coded "start with bbm.assembly_item_id = 271962", as it is the root node of a tree (BOM).
Here's my structure, with extra fields clipped out:
DBMS_METADATA.GET_DDL('TABLE','BOM_STRUCTURES_B','BOM')
CREATE TABLE "BOM"."BOM_STRUCTURES_B"
( "ASSEMBLY_ITEM_ID" NUMBER,
"ORGANIZATION_ID" NUMBER NOT NULL ENABLE,
"COMMON_BILL_SEQUENCE_ID" NUMBER NOT NULL ENABLE,
) PCTFREE 20 PCTUSED 80 INITRANS 10 MAXTRANS 255 NOCOMPRESS LOGGING
STORAGE(INITIAL 131072 NEXT 131072 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 4 FREELIST GROUPS 4 BUFFER_POOL DEFAULT)
TABLESPACE "APPS_TS_TX_DATA"
DBMS_METADATA.GET_DDL('TABLE','BOM_COMPONENTS_B','BOM')
CREATE TABLE "BOM"."BOM_COMPONENTS_B"
("COMPONENT_ITEM_ID" NUMBER,
"BILL_SEQUENCE_ID" NUMBER NOT NULL ENABLE,
"PARENT_BILL_SEQ_ID" NUMBER,
) PCTFREE 35 PCTUSED 50 INITRANS 10 MAXTRANS 255 NOCOMPRESS LOGGING
STORAGE(INITIAL 131072 NEXT 131072 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 4 FREELIST GROUPS 4 BUFFER_POOL DEFAULT)
TABLESPACE "APPS_TS_TX_DATA"
DBMS_METADATA.GET_DDL('TABLE','MTL_SYSTEM_ITEMS_B','INV')
CREATE TABLE "INV"."MTL_SYSTEM_ITEMS_B"
( "INVENTORY_ITEM_ID" NUMBER NOT NULL ENABLE,
"ORGANIZATION_ID" NUMBER NOT NULL ENABLE,
"DESCRIPTION" VARCHAR2(240),
) PCTFREE 10 PCTUSED 70 INITRANS 10 MAXTRANS 255 NOCOMPRESS LOGGING
STORAGE(INITIAL 131072 NEXT 131072 MINEXTENTS 1 MAXEXTENTS 2147483645
PCTINCREASE 0 FREELISTS 4 FREELIST GROUPS 4 BUFFER_POOL DEFAULT)
TABLESPACE "APPS_TS_TX_DATA"
The relationship between the tables is:
A BOM_STRUCTURES_B has many BOM_COMPONENTS_B where BOM_COMPONENTS_B.PARENT_BILL_SEQ_ID = BOM_STRUCTURES_B.BILL_SEQUENCE_ID. Both BOM_STRUCTURES_B.ASSEMBLY_ITEM_ID and BOM_COMPONENTS_B.COMPONENT_ITEM_ID are related to a single MTL_SYSTEM_ITEMS_B.INVENTORY_ITEM_ID.
Thanks to anyone who can help with this horrible problem I've been fighting with for much too long! :)
Thank you!
SteveDue to an error in the otn forums (*), this got posted to the wrong forum, sorry for that, I'll repost in the correct one.
*) For the forum admins: I was browsing the SQL/PLSQL forum, clicked on 'new message', got the login prompt, logged in, and apparently this got me to the application server forum for some reason. -
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.
Maybe you are looking for
-
How to search file in application server using pattern
Hi all, I want to search file in application server. Suppose there is file named abc20090808.dat. Is there is any function module to search the file? it should return back the file names starting with abc, if the import parameter is abc* Regards, Nik
-
HP Envy 5660 - Paper jam message
Our HP Envy 5660 printer is 2 weeks old. It was purchased at an electronics chain store. Set-up was easy. No issues until the second week of ownership. An error message popped up reporting a paper jam issue. Followed directions to take out the j
-
Purchase Order data extraction for Service PO
Hi Experts, I am facing problem for extraction of Service Po data .For extractor 2LIS-02_ITM which will give the item details for PO. for the same I am not geting service Number . In ITEM data its show only its service type PO . but not giving servi
-
Import a servlet from JSP without the use of a .JAR
Migrating web app from NT / iPlanet 4.1 to Solaris / iPlanet 4.1. I've created a Web app in which JSPs utilize Servlets stored in a JAR file. I am now moving the app to a server that I do not control. I wish to configure the app in such a way that I
-
Is there a contact email for ipod nano replacement program?
Thank you for any information you may be able to provide!