đź’Ľ SQL Detective Mode: Employees Earning More Than Their Managers

Ardhendu GhoshArdhendu Ghosh
2 min read

đź§© Problem Overview

In relational databases, hierarchical relationships often hold subtle insights—especially when it comes to salaries. This challenge from LeetCode, 181. Employees Earning More Than Their Managers, asks us to identify employees whose earnings surpass those of their direct managers.

The table schema is simple:

Column NameType
idint
namevarchar
salaryint
managerIdint

Each row represents an employee, their salary, and the ID of their manager. Our goal is to return the names of employees who earn more than their managers.

🔍 SQL Strategy: Self-Join

To solve this, we use a self-join—a powerful technique where a table is joined with itself to compare rows within the same dataset.

Here’s the logic:

  • Join the employee table to itself.

  • Match each employee (e2) with their manager (e1) using e2.managerId = e1.id.

  • Filter where e2.salary > e1.salary.

đź§Ş Final Query

sql

SELECT e2.name AS Employee  
FROM employee e2  
JOIN employee e1  
ON e2.managerId = e1.id  
WHERE e2.salary > e1.salary;

📊 Sample Input

idnamesalarymanagerId
1Joe700003
2Henry800004
3Sam60000NULL
4Max90000NULL

âś… Output

Employee
Joe

Joe earns more than his manager Sam—so he’s the only one returned.

đź§  Takeaway

This pattern is essential for:

  • Salary audits

  • Organizational hierarchy validations

  • Annotation logic in classification workflows

By mastering self-joins, you unlock the ability to compare hierarchical data with precision—whether you're debugging annotation pipelines or building scalable dashboards.

  • Self-Join vs. Subquery: When to use which

  • Hierarchical data modeling in SQL

  • Salary band validation using window functions

11
Subscribe to my newsletter

Read articles from Ardhendu Ghosh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ardhendu Ghosh
Ardhendu Ghosh

🧵 Stitching logic into data, culture into pixels, and clarity into workflows. I’m Ardhendu Ghosh—a systems architect in the making, blending SQL precision, annotation logic, and creative restoration into scalable, story-driven solutions. I build: 🧠 Reusable query modules for streaks, duplicates & classification 🎨 Emotionally attentive image enhancements (yes, even bindis matter) 📊 Dashboard-ready logic for annotation pipelines & public sharing ✍️ SEO-optimized content for Hashnode, LinkedIn & beyond If it’s repeatable, teachable, and culturally meaningful—I’m building it.