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

Find Every Top-Paid Employee per Job with a Row Subquery

Match each (job_id, salary) pair against grouped job maxima returned by a multi-column subquery.

  • Joins
  • Subqueries
  • Aggregation
  • Filtering
  • Sorting

Exercise brief

Understand the request

Job architecture analyst A job-level compensation review needs every employee tied at the maximum for their job code.

Find the highest-paid employee in each job_id. Use the tuple-subquery form `(job_id, salary) IN (SELECT job_id, MAX(salary) FROM employees GROUP BY job_id)`. Return employee_id, first_name, last_name, job_id, salary — ordered by job_id, employee_id.

Return

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

Constraints

  • Use row-constructor IN where supported.
  • Use the supplied grouped derived-table join on SQL Server, which lacks row-constructor IN.

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)
  • job_idVARCHAR(20)
  • salaryINTEGER

Hints, when you need them

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

Hint 1

Row-constructor IN: `(a, b) IN (SELECT x, y ...)` — matches when the WHOLE pair appears.

Hint 2

Cleaner than the correlated-MAX form (Q19) because there is no correlation.

Hint 3

SQL Server doesn't support row-constructor IN — emulate with EXISTS or a JOIN to the aggregated subquery.

Verified SQL answer

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

Reveal solution and explanation
SELECT employee_id, first_name, last_name, job_id, salary FROM employees WHERE (job_id, salary) IN (SELECT job_id, MAX(salary) FROM employees GROUP BY job_id) ORDER BY job_id, employee_id;

Why this works

Multi-column subqueries are SQL's most under-used feature. They turn 'top per group' into a single uncorrelated subquery — clean, fast, and dependable. Only SQL Server requires an emulation (EXISTS or JOIN to derived).

Success check

Every employee at the maximum salary for their job appears once and ties are preserved.

Expected result

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

employee_idfirst_namelast_namejob_idsalary
104DavidBrownFIN_ANALYST70000
103CarolDavisHR_REP60000
100JohnSmithIT_MGR120000
107GraceWhiteIT_PROG90000
105EmmaTaylorMKT_MGR95000
106FrankGreenSALES_REP65000

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.