DB2 Recursive Query

If you’ve ever had to do a recursive query in DB2 to get a hierarchy of records, feel free to use this as a starting point…

WITH LINKS (PARENT_ID, CHILD_ID, UPDATED_TS) AS 
    ( 
    SELECT  ROOT.PARENT_ID, ROOT.CHILD_ID, ROOT.UPDATED_TS 
    FROM    XX.EVENTS ROOT 
    WHERE   ROOT.CHILD_ID = '234ASDFASDF' 
        UNION ALL 
    SELECT  CHILD.PARENT_ID, CHILD.CHILD_ID, CHILD.UPDATED_TS 
    FROM    LINKS PARENT, XX.EVENTS CHILD 
    WHERE   PARENT.PARENT_ID = CHILD.CHILD_ID 
    ) 
SELECT  PARENT_ID, CHILD_ID, UPDATED_TS 
FROM    LINKS 
ORDER BY UPDATED_TS 
FOR READ ONLY WITH UR

… yes, newer versions of DB2 have this ability built in but you’re not always using the most recent version are you??

Thanks to this page for pointing me in the right direction.

Please remember to subscribe to the newsletter to stay up to date!

You or someone you know looking to buy or sell?
Disclaimer: Thoughts and opinions are my own, and do not reflect the views of any employer, family member, friend, or anyone else. Some links may be affiliate links, but I don't link to anything I don't use myself. You would think this should be self evident these days, but apparently not...

Leave a Reply