Skip to content
Quantoros

Order employees by hiredate: return name, hiredate, salary, and salary minus the previous hires salary (deltavsprev,…

SQLLevel: IntermediateWindow functions

Order employees by hire_date: return name, hire_date, salary, and salary minus the previous hires salary (delta_vs_prev, NULL for the first).

Table definitions (from the source exercise):

CREATE TABLE employees(emp_id INTEGER PRIMARY KEY, name TEXT, department_id INTEGER, manager_id INTEGER, salary INTEGER, hire_date TEXT, job_title TEXT, gender TEXT);
Hints
  • Distinguish a missing value from zero, an empty string and false.
  • Test comparison, aggregation and filtering on a tiny missing-value example.

Answer

Approach: LAG(salary) OVER (ORDER BY hire_date, emp_id).

SELECT name, hire_date, salary,
       salary - LAG(salary) OVER (ORDER BY hire_date, emp_id) AS delta_vs_prev
FROM employees;

The source uses SQLite with a MySQL compatibility layer. Date and string functions are dialect dependent; the query is preserved as published.

Source and licence: SQL Practice Lab — Ebrahim Sharifi · MIT

Related questions