Tree query in Oracle

Source: Internet
Author: User

Basic syntax

Select... from tabename start with cond1 connect by prior cond2 where cond2

Note: cond1 is the limit statement for the root node.

Cond2 is the connection condition, where prior indicates the previous record, indicating that the father of the record is the previous record

Cond3 is a filter condition.

Build an environment: you do not know

Create Table Family (
Id integer,
Parentid integer,
Name varchar2 (50)
)

Insert into family values (0, 0, 'A ')
Insert into family values (1, 0, 'B ')
Insert into family values (2, 1, 'C ')
Insert into family values (3, 1, 'D ')
Insert into family values (4,1, 'E ')
Insert into family values (5, 1, 'F ')

Example 1: traverse sub-nodes through the root node

-- Query the information of all the children whose father is equal to 1
Select * from Family Start With parentid = 1 connect by prior id = parentid

Example 2: Tracing to the root node through a subnode

Select * from Family Start with ID = 5 connect by prior parentid = ID

Note: If the ORA-01436 is reported: The coonect by loop in the user database, the parentid In the first data is changed to null, otherwise the loop find parentid will not find it!

Extension:PassLevelLevel of keyword Query

Select T. *, level from family t start with parentid = 1 connect by prior id = parentid -- the table must use an alias

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.