SQL interview question: recursive employee hierarchy

MediumHierarchies and recursion

Problem

Shared data rules

For each employee in couriers, find their level and reporting line — from the employee up to the top.

Example

Input: couriers
courier_idrolemanager_idfired_atRow note
1head_of_logisticsNULLNULL
2city_lead1NULL
4supervisor22026-08-14← dismissed
5supervisor2NULL
57courier4NULL
58courier52026-09-03← dismissed
Output
courier_iddepthchain
101
212 > 1
424 > 2 > 1
525 > 2 > 1
57357 > 4 > 2 > 1
58358 > 5 > 2 > 1

Courier 57’s line passes through supervisor 4: '57 > 4 > 2 > 1', level 3. The top, 1, has the line '1'.

Output columns

depth
how many managers are above the employee; 0 for the top
chain
IDs from the bottom up joined by “ > ”

Notes

Solve it free

Your query runs on PostgreSQL in your browser. No sign-up needed.

Skills it tests

More interview questions

All questions