HardSQL challenge #377GROUP BYSTATISTICSANALYSIS

Balanced Salary Departments

Find departments with lowest salary variance.

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 departments with lowest salary variance.

A correct answer returns 10 rows with 2 columns: department, variance.

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
departmentvariance
Legal1444484264.375
HR1497162267.2430573
Product1592878515.5555553
Sales1959498976.4462814
Customer Success2141350346.8622246
Finance2275050906.200001
Engineering2447998886.363636
Marketing2544650914.8994083
Operations2630926051.5147934
Design2977009917.09

The complete result: 10 rows. This is the output of the model solution on the practice database.

What you practise

  • Summarising many rows into one value with COUNT, SUM, AVG, MIN or MAX
  • Grouping rows with GROUP BY to get one result row per group
  • 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

variance formula

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.
  2. Group the rows by department, so the result has one row for each value.
  3. For each group, compute AVG(salary*salary) and AVG(salary).
  4. Calculate variance from those aggregates: AVG(salary*salary) - AVG(salary)*AVG(salary).
  5. Sort the result by variance.

Model solution

Checking your session…

What to watch for

  • GROUP BY. Every selected column must either be in GROUP BY or sit inside an aggregate. SQLite accepts other columns and returns an arbitrary value for them; most databases raise an error.
  • Calculated columns. Dividing one integer by another truncates the result in SQLite. Multiply one side by 1.0 to get decimals.
  • ORDER BY. Without ORDER BY the row order is not guaranteed, even if it looks stable. Rows that tie on the sort columns can come back in any order.
Solve This SQL Challenge

Keep learning