Question about common table expression and father-child



IBM's flagship relational database management system

Question about common table expression and father-child

Postby KofKof » Wed Nov 21, 2012 4:31 pm

Hello guys,

When i use the common-table-expression keyword WITH, where does the defined data reside? or DB2 just replaces the WITH table with the sql?
for example

with mytable as (select * from sysibm)
Select * from mytable

In DB2 v10, is there an easy way (like in oracle) to define father-child reletionship? or it is just a recursive function with the WITH clause.

Thanks alot,

P.S
Anyone encountered -725 sql error while rebinding the DRDA protocol?
KofKof
 
Posts: 1
Joined: Tue Nov 20, 2012 9:01 pm
Has thanked: 0 time
Been thanked: 0 time

Re: Question about common table expression and father-child

Postby engh » Tue Jan 28, 2025 12:51 pm

This is an old question, but I'm going to answer it anyway, because many people still ask themselves the same question today.

A Common Table Expression (CTE) is simply an externalized derived table.

For example, instead of writing :

select Col1
     , Col2
     , [...]
     , Coln
from (select ColA as Col1
           , ColB as Col2
           , [...]
           , ColX as Coln
      from My_view
     ) as Derived_table


you may write :

with Derived_table as
    (select ColA as Col1
           , ColB as Col2
           , [...]
           , ColX as Coln
      from My_view
     )
select Col1
     , Col2
     , [...]
     , Coln
from Derived_table


the advantages are :
  • the possible mutualization of the derived table when it is used several times in the same query
  • the simplification of the writing of the main query

It is also important to know that CTEs are the only solution for writing recursive queries.

Because CTE is only a derived table, there are no specific storage consideration. Data are only stored in the tables and buffered in RAM as usual.
engh
 
Posts: 17
Joined: Fri Jul 08, 2022 7:29 pm
Has thanked: 0 time
Been thanked: 1 time

Re: Question about common table expression and father-child

Postby sergeyken » Tue Jan 28, 2025 7:03 pm

CTE from WITH clause can be considered as "local VIEW definition".
It works almost in the same manner as regular VIEW, but it only exists during the query execution where its corresponding WITH clause located.
Javas and Pythons come and go, but JCL and SORT stay forever.
User avatar
sergeyken
 
Posts: 453
Joined: Wed Jul 24, 2019 10:12 pm
Has thanked: 8 times
Been thanked: 40 times


Return to DB2

 


  • Related topics
    Replies
    Views
    Last post