Skip to Main Content

Breadcrumb

Question and Answer

Connor McDonald

Thanks for the question, raj.

Asked: January 14, 2017 - 6:05 am UTC

Last updated: January 15, 2017 - 5:06 am UTC

Version: 11g

Viewed 1000+ times

You Asked

HI TOM,

I need a small short and brief explanation of the below query.

create table t as
select dbms_random.string('a', 10) y
from dual connect by level <= 10;

---Here can i know what does "connect by level" can you explain a bit brief manner why do we use connect by level !!----

select rownum, y, row_number() over (order by y) rn
from t
order by y;

ROWNUM Y RN
5 EUKmelzlob 1
10 JOgLmNyDwZ 2
2 SqfQTVqevy 3
7 jCHOIdsKuX 4
4 jYqTLBfeEY 5
1 kfvwyqSjYo 6
3 leDMxUJXKs 7
6 sViDShAFUI 8
8 tvzGkPPCxm 9
9 wBtsvBGqYg 10

and Connor said...

CONNECT BY was originally intended (and still is used) for traversing a hierarchy. For example, if your employee table is:

SQL> desc scott.emp
 Name                                      Null?    Type
 ----------------------------------------- -------- --------------
 EMPNO                                     NOT NULL NUMBER(4)
 ENAME                                              VARCHAR2(10)
 JOB                                                VARCHAR2(9)
 MGR                                                NUMBER(4)
 HIREDATE                                           DATE
 SAL                                                NUMBER(7,2)
 COMM                                               NUMBER(7,2)
 DEPTNO                                             NUMBER(2)


Then an EMPNO might also be a MGR (manage) who is themselves an employee and so forth.

So query-wise, you want to be able to:

- start with an employee
- find their manager
- "loop back" and lookup that manager as an *employee*
- find *their* manager

and so forth. We use CONNECT BY for that

SQL> select empno, ename, mgr
  2  from   scott.emp
  3  start with ename = 'SMITH'
  4  connect by empno = prior mgr;

     EMPNO ENAME             MGR
---------- ---------- ----------
      7369 SMITH            7902
      7902 FORD             7566
      7566 JONES            7839
      7839 KING

4 rows selected.


So Smith reports to Ford, who reports to Jones, who reports to King.

Someone came up with the simple idea that if we use a CONNECT BY that always "succeeds", we can generate an infinitely large data set, eg

SQL> select rownum from dual
  2  connect by 1=1;           -- always true

    ROWNUM
----------
         1
         2
         3
         4
         5
 ...
 ...


The "connect by level" is just a variation on that them.

select level from dual connect by level <= n;

will return rows with values 1 .. n

Is this answer out of date? If it is, please let us know via a Comment

More to Explore

Analytics

Analytic SQL got you confused? Check out Connor McDonald's complete video course.