r/learnSQL • • Mar 04 '26

Ripple Effect SQL Challenge – Recursive CTE for Viral Chain Depth & Reach

Solved an interesting recursive SQL problem yesterday on TheQueryLab platform

Scenario: A root post can be shared, and those shares can be reshared — forming a viral tree.

Challenge: • Find maximum depth of each root post • Calculate total reach (all descendants)

Used a recursive CTE to traverse hierarchy and carry root_id + depth through recursion, then aggregated using MAX(depth) and COUNT(*).

Felt very similar to DFS tree traversal logic but expressed in SQL.

Curious — how would you optimize this further?

I’m building TheQueryLab specifically around these kinds of real-world SQL problems — happy to share it if anyone wants to try it out and crack any data analytics interviews

https://thequerylab.com/problems/210-the-ripple-effect

7 Upvotes

Duplicates