CTEs & Window Functions SQL practice problemMediumVerified answer

Delta From Starting Salary (FIRST_VALUE)

For each salaries_history record, show how far the salary has moved from the employee's very first recorded salary. Return employee_id, effective_date, salary, starting_salary, delta_from_start — ordered by employee_id, effective_date.

  • Window functions
  • Sorting

Interview brief

Understand the request

For each salaries_history record, show how far the salary has moved from the employee's very first recorded salary. Return employee_id, effective_date, salary, starting_salary, delta_from_start — ordered by employee_id, effective_date.

Data you will use

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

salaries_history

  • employee_idINTEGER
  • salaryINTEGER
  • effective_dateDATE

Hints, when you need them

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

Hint 1

FIRST_VALUE is safe with the default frame (the partition start never moves).

Hint 2

delta_from_start = current salary − first salary; the first row is always 0.

Hint 3

This is cohort analysis: every record measured against a fixed baseline.

Verified SQL answer

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

Reveal solution and explanation
SELECT employee_id, effective_date, salary, FIRST_VALUE(salary) OVER (PARTITION BY employee_id ORDER BY effective_date) AS starting_salary, salary - FIRST_VALUE(salary) OVER (PARTITION BY employee_id ORDER BY effective_date) AS delta_from_start FROM salaries_history ORDER BY employee_id, effective_date;

Why this works

Indexing every row to a fixed baseline (the first value) is the heart of cohort and 'growth since start' analysis. Unlike LAST_VALUE, FIRST_VALUE works with the default frame because the partition's start is always in view.

Expected result

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

employee_ideffective_datesalarystarting_salarydelta_from_start
42020-02-141100001100000
42021-02-1412000011000010000
42022-02-1413000011000020000
52020-05-181050001050000
52021-05-1811500010500010000
52022-05-1812500010500020000
62021-01-1085000850000
62022-01-10950008500010000
82020-08-1595000950000
82021-08-151050009500010000

Previewing 10 of 13 expected rows. Run the query in the editor to inspect the full result.

Learn the concepts behind this answer

Strengthen your understanding with these targeted learning topics: