Guest Post
- Author – Saurabh Gupta
In this post we will go through recursive query with one example.
The recursive query features enables to query hierarchical data such as an organisation chart or bill of materials ( check the raw materials used to make a product ). Using Recursive query data with in the single table can be scanned multiple times using a single SQL statement.
A recursive query is useful when relationships between data elements exist in multiple iterations. Recursive query consist of two parts a seeding query and a recursive query. Seeding query provides the initial records for which data needs to be iterated whereas Recursive query part helps in data iteration.
We will be using below syntax for recursive query :
Recursive query syntax :
WITH RECURSIVE < recursive_tablename > (<columnname 1>,<columnname 2>,….<columnname n>) AS ( <SELECT * from seed_table> UNION ALL <select * from recursive_tablename join seed_table> ) <SELECT * FROM recursive_tablename>;
1) Recursive_tablename is a derived recursive table defined using WITH RECURSIVE keyword.
2) Column names of recursive table is specified as <columname >. This column names will be finally displayed in the output.
3) Seeding query ( query which is used as the input for recursive logic ) is mentioned as the first select statement.
4) Second select statement is known as the recursive query and is joined with seed table for multiple iterations.
5) Third select statement finally gives the output of recursive logic.
Let’s consider a table, Employee ( ddl shown below ) which stores –
CREATE VOLATILE TABLE Employee ( EMP_ID INTEGER, MGR_ID INTEGER, EMP_NAME VARCHAR(100) ) ON COMMIT PRESERVE ROWS;
Employee Id in column EMP_ID , Employee’s manager Id in column MGR_ID and Employee Name in column EMP_NAME e.g. Zoya is an employee with Employee Id 28006 and her direct Manager Id is 28005 .
One day Zoya wants to find out her first level, second level managers in the hierarchy i.e. all the direct and indirect manager above her in the hierarchy. Since employee table stores only first level of hierarchy (i.e. the direct manager which is employee id 28005 ( Patrick ) in case of Zoya), to find the hierarchy she needs to query database multiple times .This can be achieved very easily using a recursive query within a single sql statement.
WITH RECURSIVE MGR_JRS (EMP_ID, MGR_ID, MGR_NAME, DEPTH) AS ( SELECT EMPL.EMP_ID, EMPL.MGR_ID, EMPL1.EMP_NAME AS MGR_NAME, 1 AS DEPTH FROM Employee empl inner join Employee empl1 on empl.mgr_id = empl1.emp_id WHERE empl.EMP_ID=28006 UNION ALL SELECT MGR_JRS.EMP_ID, EMPL.MGR_ID, empl1.EMP_NAME, MGR_JRS.DEPTH + 1 FROM MGR_JRS INNER JOIN Employee empl ON MGR_JRS.MGR_ID = EMPL.EMP_ID inner join Employee empl1 on empl.mgr_id = empl1.emp_id ) SELECT * FROM MGR_JRS;
Below points explains the above sql :
1) WITH RECURSIVE keyword specifies table MGR_JRS is a derived recursive table.
2) The first select statement :
SELECT EMPL.EMP_ID, EMPL.MGR_ID, EMPL1.EMP_NAME AS MGR_NAME, 1 AS DEPTH FROM Employee empl inner join Employee empl1 on empl.mgr_id = empl1.emp_id WHERE empl.EMP_ID=28006
![]()
gives the Manager name and manager employee Id for Employee ID 28006 ( for Zoya ). So the first level manager for Zoya identified by above sql is Patrick. Data retrieved using above sql is internally stored in derived table MGR_JRS. This is often referred as seeding query.
3) Second select joins Employee table to MGR_JRS table which is getting populated as part of recursive logic. This is often referred as recursive query.
SELECT MGR_JRS.EMP_ID, EMPL.MGR_ID, empl1.EMP_NAME, MGR_JRS.DEPTH + 1 FROM MGR_JRS INNER JOIN Employee empl ON MGR_JRS.MGR_ID = EMPL.EMP_ID inner join Employee empl1 on empl.mgr_id = empl1.emp_id
Since MGR_JRS has one record with MGR_ID 28005 , it joins with employee table where EMP_ID is 28003 and in turn saves one more row in MGR_JRS.
Now Zoya knows her second level manager is Lorena.
4) Each time a new row is added to MGR_JRS, the possibility exists for a new match and thus a higher level manager will be found in hierarchy.
5) It will recursively execute this join operation until it has found all managers for Zoya.
6) When the WITH table population is completed i.e. Step 5 is completed, the final SELECT will execute producing the below output.
In this case Zoya has four levels of manager above her in the organization chart. Thus, a complex requirement of multiple iteration is very easily solved using recursive query.
Limitations :
Following are not allowed in recursive portion of query but allowed in seeding portion :
- Subqueries and derived tables
- Aggregation and OLAP functions
- NOT IN and NOT EXISTS
- GROUP BY and extended grouping functions
- DISTINCT
TOP N function ,Cursors ,Stored procedures,Triggers are not permitted in recursive query
Summary :
The recursive query feature enables multiple iterations against hierarchical data in a single SQL statement.
If you like the post do share it on your social networking sites with the below share button 🙂






40 comments
10 pings
Skip to comment form
kvcbgy
AGHoaYmtJbYsamBvIZPWBMCt
You made some really good points there. I checked on the web for more info about the issue and found most people will go along with your views on this web site.
These are truly great ideas in regarding blogging. You have touched some fastidious points here. Any way keep up wrinting.
I really like what you guys are up too. This kind of clever work and exposure! Keep up the excellent works guys I’ve added you guys to our blogroll.
Thanks for a marvelous posting! I quite enjoyed reading it, you can be a great author.I will remember to bookmark your blog and definitely will come back later in life. I want to encourage one to continue your great work, have a nice holiday weekend!
I just couldn’t depart your web site prior to suggesting that I really loved the usual information an individual supply to your guests? Is going to be back steadily to check up on new posts
Ahaa, its fastidious conversation on the topic of this paragraph here at this website, I have read all that, so at this time me also commenting at this place.
I am sure this article has touched all the internet users, its really really good piece of writing on building up new website.
It’s verdy eeffortless tto fijnd ouut any matter oon wweb aas compared to books, as I ound tthis piece off writing at this wweb page.
It’s very trouble-free to find out any matter on net as compared to books, as I found this piece of writing at this site.
Everyone loves what you guys tend to be up too. Such clever work and coverage! Keep up the great works guys I’ve included you guys to my own blogroll.
That’s a solid point about game accessibility! Seeing platforms like betpk online casino integrate GCash & PayMaya is smart for the PH market – quick deposits are key for enjoying slots & sports! 👍
There is visibly a lot to identify about this. I suppose you made certain good points in features also.
Sup folks! jljl533 looks legit enough. Have a gander at jljl533
https://shorturl.fm/qn4SH
Gave xsmbxoso666 a try and it’s pretty interesting! Different from what I’m used to, but in a good way. Games are running well and the site is easy to use. Worth a look! xsmbxoso666
https://shorturl.fm/SL1Qm
Downloaded the ee88app app and it’s actually pretty sweet. Super easy to use and gets the job done. Worth a download, for sure. Check it: ee88app
ymu6xu
https://shorturl.fm/hE3W0
https://shorturl.fm/qRcQW
https://shorturl.fm/iduzP
https://shorturl.fm/09PMZ
https://shorturl.fm/YcE20
Is there any way can we implement the Recursive functionality without using recursive keyword. We are migrating TD Sqls to hive which doesn’t support recursive functionality.
Thank you in advance.
Anybody have a recursive to get the database ownership hierarchy in DBC.Databases? I wrote one but is is a dog…
Lock
Row
For
Access
WITH RECURSIVE DB
(DatabaseName, OwnerName)
AS
(
SELECT D.DatabaseName, D.OwnerName from DBC.Databases D
UNION ALL
select DB.DatabaseName, DB.OwnerName from DB join DBC.Databases D
On
DB.DatabaseName = D.OwnerName
)
SELECT * FROM DB;
Why do delete is not working in recursive queries of Teradata ?
Hi admin you have described fastload as load as like that am looking for all utilities
are bteq,multiload,tpump,tpt,fastexport. Please give a explanation as soon as possible we are waiting for explanations.
if any one have TD training videos please share the links.
Shelza,
Your logic is in the right direction. But you need to have partition on first column EID.Also in Case statements it should be changed :
Select
x.EID,
Max(Case when x.rn=1 then Address End) As Address1,
Max(Case when x.rn=2 then Address End) As Address2,
Max(Case when x.rn=3 then Address End) As Address3
From
(
Select
EID,
Address,
row_number() (over partition by EID order by Address asc) rn
From
) x;
Thanks Guys, keep following the others posts on TeradataTech.
Its answer would be:
Select x.EID,
case when x.rn=1 then address end as address1,
case when x.rn=1 then address end as address2,
case when x.rn=1 then address end as address3
from
(select row number() over (order by EID) as rn from table)x;
Awwesome explanation
Wow very nice explanation with universable employee table.
How to convert the vertical data into horizantal data
EX:
EID Address
101 New york
101 London
101 JAPAN
I want the data like this
EID Addrss1 Address2 Address3
101 New york London JAPAN
Please let me know if you know the ans.
select
EID
,Max( case when Address = ‘New York’ then ‘New York’ end) as Address1
,Max( case when Address = ‘London’ then ‘London’ end) as Address2
,Max( case when Address = ‘JAPAN’ then ‘JAPAN’ end) as Address3
from
catch here to know all the values of address beforehand, in above query we assume that address column has only 3 distinct values as – New york, London, JAPAN
Clear understanding with simple example..
Good example with Very nice explanation.
doxycycline for acne dosage
doxycycline for acne dosage
kamagra kaunas
kamagra kaunas
semaglutid i mat
semaglutid i mat
avanafil where to buy
avanafil where to buy
lasix diuretic over the counter
lasix diuretic over the counter
lasix diuretic medicine
lasix diuretic medicine
lasix furosemide 40 mg
lasix furosemide 40 mg
rifampin medication
rifampin medication
zyvoxam
zyvoxam
finasteride minoxidil
finasteride minoxidil