#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
Step 17
4 min read

Recursive Queries

Learn recursive CTEs - queries that call themselves!

What is a Recursive Query?

Employee Hierarchy Example
idnamemanager_idlevel
1CEONULL1
2VP12
3Manager23
4Employee34
4 rows

A query that calls itself repeatedly until done.

Example: Org Chart

Employee Hierarchy Example
idnamemanager_idlevel
1CEONULL1
2VP12
3Manager23
4Employee34
4 rows
WITH RECURSIVE org AS ( -- Start: Get top person SELECT id, name, 1 AS level FROM employees WHERE manager_id IS NULL UNION ALL -- Repeat: Get their reports SELECT e.id, e.name, o.level + 1 FROM employees e JOIN org o ON e.manager_id = o.id ) SELECT * FROM org;

How it works:

  1. Get CEO (level 1)
  2. Find people reporting to CEO (level 2)
  3. Find people reporting to them (level 3)
  4. Repeat until no more

Use Cases

Employee Hierarchy Example
idnamemanager_idlevel
1CEONULL1
2VP12
3Manager23
4Employee34
4 rows
  • Organization hierarchies
  • Category trees (Electronics > Phones > iPhone)
  • File/folder structures
  • Any parent-child data

Summary

Employee Hierarchy Example
idnamemanager_idlevel
1CEONULL1
2VP12
3Manager23
4Employee34
4 rows
  • WITH RECURSIVE: Query calls itself
  • First part: Starting point
  • UNION ALL: Combine results
  • Second part: Find next level

Finished this topic?

Mark it complete to track your progress and maintain your streak!