HardSQL challenge #312SELF JOINCALCULATIONORDER BY

Compare Each Employee's Salary with Their Manager's

Return each employee with the difference between their salary and their manager's, largest first.

The challenge runs on the SQLabHub practice database (SQLite) and uses the employees table. You can solve it in the browser, with nothing to install.

Solve This SQL Challenge

The task

Find employees with highest salary difference compared to manager.

A correct answer returns 110 rows with 2 columns: id, diff.

Tables used in this challenge

employees 120 rows

id INTEGER (PK) · first_name TEXT · last_name TEXT · email TEXT · department TEXT · department_id INTEGER · title TEXT · salary REAL · hire_date TEXT · manager_id INTEGER · city TEXT · status TEXT

First 3 rows of the employees table
idfirst_namelast_nameemaildepartmentdepartment_idtitlesalaryhire_datemanager_idcitystatus
1WilliamLewiswlewis18@corp.ioCustomer Success7Senior CS Manager617742022-07-24NULLSan Diegoactive
2JohnMillerjmiller51@corp.ioLegal8Paralegal1916942021-08-09NULLSan Diegoactive
3DanielRiveradrivera50@corp.ioEngineering1VP Engineering1350672016-06-06NULLHoustonactive

The first rows of each table are shown. See how all the tables relate on the database schema page.

Expected output

Expected output of the challenge
iddiff
50144567
73140192
11133985
82131219
111120847

First 5 of 110 rows. This is the output of the model solution on the practice database.

What you practise

  • Combining rows from two tables on a matching key with an inner join
  • Joining a table to itself under two aliases
  • Sorting the result with ORDER BY
  • Deriving a new column from an expression and naming it with an alias

Hint and approach

Try the challenge first. Open these only when you need them.

Show the hint

Self join difference

Show the step-by-step approach

How the model solution is built, in the order the database evaluates it:

  1. Read from the employees table, under the alias e.
  2. Join employees again, under the alias m, on e.manager_id = m.id.
  3. Add the calculated column diff: e.salary - m.salary.
  4. Sort the result by diff descending.

Model solution

Checking your session…

What to watch for

The inner self join matches each employee to the row of their manager and drops the ten people who have none. A positive difference means the employee earns more than the manager.

  • Self join. Without a condition such as a.id < b.id, a self join pairs every row with itself and lists each pair twice.
  • INNER JOIN. An inner join drops rows that have no partner on the other side, and it repeats a row once for every match, which inflates SUM and COUNT.
  • Calculated columns. Dividing one integer by another truncates the result in SQLite. Multiply one side by 1.0 to get decimals.
Solve This SQL Challenge

Keep learning