Save up to $499! Grab all Python courses for $49 or all online courses we’ve ever launched for only $169. Only Feb 11-16. Happy Valentine's!
Introduction
The very basics
Infinite looping
Processing trees with recursive CTE
Processing graphs with recursive CTE
Summary

Instruction

Great. Now that you got the basics, we will learn some real-world examples.

Let's say we have a company with a hierarchical structure, i.e. each employee has a superior (except for the boss). An employee has precisely one superior, but one superior may have multiple inferiors. An example structure may look as follows:

recursion

In computer science, we call such a structure a tree, where each node (employee) has a parent node (superior), except for the root (boss), which has no parent node.

How can we store these hierarchical relations in a database? It's quite simple: each employee is represented with a row that has a column superior_id with the id of their superior.

recursion

Take a look at our table.

Exercise

Select all data from table employee.

As you can see, the table has the following columns:

  • id - idetifier of employee,
  • first_name - first name of employee,
  • last_name - last name of employee,
  • superior_id - identifier of person above employee.