Author: Michał Kołodziejski

Senior Software Engineer, Team Leader

Get to Know the Power of SQL Recursive Queries

Business People with Winner Shadow. Male and Female Characters with Silhouettes of Leadership, Achievement and Motivation.
Level: Advanced Most commonly, the SQL queries we run on a database are quite simple. Well, that depends on your role, of course. Analysts in data warehouses retrieve completely different sorts of information using (very often) much more complicated queries than software engineers creating CRUD applications. However, sometimes it’s simpler or more elegant to run a query that is a little bit more sophisticated without needing further data processing in the code.

Do It in SQL: Recursive Tree Traversal

In the previous article, I described how to use Common Table Expressions to find the shortest path in a directed graph. That example could be hard to follow, I admit. Let’s do something much more common, something that is implemented on almost every website – a menu. But… we’ll do as much as possible in a single SQL query instead of writing the code. We’ll use CTEs for PostgreSQL and the hierarchical query clause for Oracle.