Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect by in Oracle SQL

Suppose that we have following tables

create table Employee(
  2    EMPNO         NUMBER(3),
  3    ENAME         VARCHAR2(15 BYTE),
  4    HIREDATE      DATE,
  5    ORIG_SALARY   NUMBER(6),
  6    CURR_SALARY   NUMBER(6),
  7    REGION        VARCHAR2(1 BYTE),
  8    MANAGER_ID    NUMBER(3)
  9  )

and

create table job (
  2    EMPNO         NUMBER(3),
  3    jobtitle      VARCHAR2(20 BYTE)
  4  )
  5  /

I am interested in what the below query does

SELECT empno, manager_id, ename
  2  FROM employee
  3  START WITH empno = 1
  4  CONNECT BY PRIOR empno = manager_id;

As I understood this code selects empno,manager_id,ename from employee, it starts selection from this row where empno=1, but could not understand what this line does:

CONNECT BY PRIOR empno = manager_id;

Is this the same as:

where empno=manager_id?
like image 473
dato datuashvili Avatar asked Jun 21 '12 06:06

dato datuashvili


People also ask

What is level in Connect by?

LEVEL is a pseudocolumn that returns the ordinal number of the recursive step in the Hierarchic clause that returned the row. For all the rows returned by the START WITH clause, LEVEL return the value 1 . Rows that are returned by applying the first iteration of the CONNECT BY clause return 2.

What does (+) mean in Oracle join?

The plus sign is Oracle syntax for an outer join. There isn't a minus operator for joins. An outer join means return all rows from one table. Also return the rows from the outer joined where there's a match on the join key. If there's no matching row, return null.

How does connect by work?

"connect by" -- describes how to walk from the parent nodes above to their children and their childrens children. that will take all of the PRIOR records (the start with at first) and find all records such that the MGR column equals their EMPNO (find all the records of people managed by the people we started with).

Can I use GROUP BY in Oracle?

In Oracle GROUP BY clause is used with SELECT statement to collect data from multiple records and group the results by one or more columns.


2 Answers

CONNECT BY PRIOR empno = manager_id;

This will produce the recursion. All records that are part of the next lower hierarchical level will return. This will return a hierarchy from top to bottom for all managers and their respective under working subordinates.

30 (manager_id)
   12 
   5 (manager_id)
      1
      7
20 (manager_id)
   15
   10
like image 187
manurajhada Avatar answered Sep 29 '22 16:09

manurajhada


The query is recursive, it start from employee #1 (CEO probably) and then recursively prints all his subordinates and then all their subordinates and so on and so forth (until all the employees are printed).

A good explanation about the "START WITH" and "CONNECT BY" can be found here

like image 44
Nir Alfasi Avatar answered Sep 29 '22 15:09

Nir Alfasi