CTEs & Window Functions SQL practice problemMediumVerified answer

Keep Only the Latest Salary Per Employee (Deduplication)

salaries_history holds multiple rows per employee. Keep only the most recent record per employee (latest effective_date). Use ROW_NUMBER. Return employee_id, salary, effective_date — ordered by employee_id.

  • CTEs
  • Window functions
  • Subqueries
  • Filtering
  • Sorting

Interview brief

Understand the request

salaries_history holds multiple rows per employee. Keep only the most recent record per employee (latest effective_date). Use ROW_NUMBER. Return employee_id, salary, effective_date — ordered by employee_id.

Data you will use

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

salaries_history

  • salary_idINTEGER
  • employee_idINTEGER
  • salaryINTEGER
  • effective_dateDATE

Hints, when you need them

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

Hint 1

Deduplication = ROW_NUMBER partitioned by the dedup key, ordered so the row you want to keep is rn = 1.

Hint 2

Here newest-first: ORDER BY effective_date DESC.

Hint 3

Add a tie-breaker (salary_id) if two rows could share an effective_date.

Verified SQL answer

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

Reveal solution and explanation
WITH ranked AS (SELECT employee_id, salary, effective_date, ROW_NUMBER() OVER (PARTITION BY employee_id ORDER BY effective_date DESC) AS rn FROM salaries_history) SELECT employee_id, salary, effective_date FROM ranked WHERE rn = 1 ORDER BY employee_id;

Why this works

Deduplication is the #1 real-world use of window functions in ETL. ROW_NUMBER over the key, ordered by recency, then keep rn = 1 — far cleaner and faster than a correlated MAX-date subquery.

Expected result

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

employee_idsalaryeffective_date
41300002022-02-14
51250002022-05-18
6950002022-01-10
81100002022-08-15
9750002022-06-01

Learn the concepts behind this answer

Strengthen your understanding with these targeted learning topics: