Oracle CONNECT BY - only returning first level item

CJM picture CJM · Mar 14, 2012 · Viewed 8.6k times · Source

I'm trying to select a parent product and all of it's child products; explode the Bill Of Materials (BoM), if you will. This should be a be simple enough task, but I'm not getting the expected result.

SELECT LEVEL,
   serial_no,
   part_no
FROM ifsapp.part_serial_catalog_tab
   START WITH serial_no       = 'Serial1'
   AND part_no                = 'ParentPart'
   CONNECT BY PRIOR serial_no = superior_serial_no
   AND part_no                = superior_part_no;

I would expect to see the following results:

1 Serial1 ParentPart
2 Serial1 ChildPart1
2 Serial2 ChildPart2

..however, I am only getting the first row (Parent) returned.

NOTE: The table has a composite key of part_no/serial_no, and as you can see from this example, the parent usually inherits the serial_no from one of the children. I'm not sure that either of these issues should complicate matters much, but clearly something is going wrong.

Why is my query not drilling down through the full hierarchy?

Answer

CJM picture CJM · Mar 14, 2012

A colleague has helped me to the solution:

SELECT LEVEL,
   serial_no,
   part_no
FROM ifsapp.part_serial_catalog_tab
   START WITH serial_no       = 'Serial1'
   AND part_no                = 'ParentPart'
   CONNECT BY PRIOR serial_no = superior_serial_no
   AND PRIOR part_no          = superior_part_no;

All the examples I've seen refer to tables with a simple key. With a composite key such as this, yes I do need to specify a relationship between both columns, but I also need the second PRIOR keyword:

   CONNECT BY PRIOR serial_no = superior_serial_no
   AND PRIOR part_no          = superior_part_no;

My SQL was syntactically correct, but not for the query I thought I was running!