SQL Subqueries SQL Topic exerciseEasyVerified answerSQLite + PostgreSQL + MySQL + SQL Server live · 1 guided

Show Each Salary Against the Company Average

Use a scalar subquery in the SELECT list to calculate company_avg and salary_minus_avg for every employee.

  • Subqueries
  • Aggregation
  • Sorting

Exercise brief

Understand the request

Compensation reporting lead A review worksheet needs row-level salary, company average, and the signed difference on the same row.

Show every employee with their salary, the company average, and the delta (salary − avg). The company average is computed via a scalar subquery in the SELECT list. Return employee_id, first_name, last_name, salary, company_avg, salary_minus_avg — ordered by salary DESC, employee_id.

Return

  • Return employee_id, first_name, last_name, salary, company_avg, salary_minus_avg in this exact left-to-right order.

Constraints

  • Keep one row per employee.
  • The company average must come from a SELECT-list scalar subquery.

Data you will use

Review the relevant tables before deciding how to join, filter, or aggregate them.

employees

  • employee_idINTEGER
  • first_nameVARCHAR(50)
  • last_nameVARCHAR(50)
  • salaryINTEGER

Hints, when you need them

Open one clue at a time so you still do the reasoning.

Hint 1

Same scalar subquery can be reused — the engine caches the value (uncorrelated).

Hint 2

The cleanest way to show 'this row vs the global aggregate' on a single result set.

Hint 3

Modern alternative: a window aggregate `AVG(salary) OVER ()` (no PARTITION BY) — same effect.

Verified SQL answer

Attempt the problem first, then compare structure and reasoning—not just syntax.

Reveal solution and explanation
SELECT e.employee_id, e.first_name, e.last_name, e.salary, (SELECT AVG(salary) FROM employees) AS company_avg, e.salary - (SELECT AVG(salary) FROM employees) AS salary_minus_avg FROM employees e ORDER BY e.salary DESC, e.employee_id;

Why this works

Scalar subqueries in SELECT are perfect for 'compare each row to a global metric'. They are uncorrelated, so they run once and cache. Window aggregates with empty OVER() are the modern equivalent.

Success check

Every employee appears once with the same computed average and a correct signed delta.

Expected result

Use this output to verify values, aliases, ordering, and row count.

employee_idfirst_namelast_namesalarycompany_avgsalary_minus_avg
100JohnSmith1200007880041200
105EmmaTaylor950007880016200
107GraceWhite900007880011200
101AliceJohnson85000788006200
102BobWilson80000788001200
104DavidBrown7000078800-8800
109IvyMartinez6800078800-10800
106FrankGreen6500078800-13800
103CarolDavis6000078800-18800
108HenryClark5500078800-23800

Learn the concepts behind this answer

Strengthen your understanding with these targeted learning topics:

Continue practicing

SQL Practice Online

Open the interactive workspace and practice across SQL topics.