HardSQL challenge #216WINDOW FUNCTIONLAGDATE

Hiring Gaps

Find gap in days between hires.

The challenge runs on the SQLabHub practice database (SQLite) and uses the employees table. You can solve it in the browser, with nothing to install.

Solve This SQL Challenge

The task

Find gap in days between hires.

A correct answer returns 120 rows with 3 columns: id, hire_date, julianday(hire_date) - julianday(LAG(hire_date) OVER (ORDER BY hire_date)).

Tables used in this challenge

employees 120 rows

id INTEGER (PK) · first_name TEXT · last_name TEXT · email TEXT · department TEXT · department_id INTEGER · title TEXT · salary REAL · hire_date TEXT · manager_id INTEGER · city TEXT · status TEXT

First 3 rows of the employees table
idfirst_namelast_nameemaildepartmentdepartment_idtitlesalaryhire_datemanager_idcitystatus
1WilliamLewiswlewis18@corp.ioCustomer Success7Senior CS Manager617742022-07-24NULLSan Diegoactive
2JohnMillerjmiller51@corp.ioLegal8Paralegal1916942021-08-09NULLSan Diegoactive
3DanielRiveradrivera50@corp.ioEngineering1VP Engineering1350672016-06-06NULLHoustonactive

The first rows of each table are shown. See how all the tables relate on the database schema page.

Expected output

Expected output of the challenge
idhire_datejulianday(hire_date) - julianday(LAG(hire_date) OVER (ORDER BY hire_date))
482015-01-14NULL
1182015-02-1633
702015-02-2610
1112015-03-1921
332015-04-2436

First 5 of 120 rows. This is the output of the model solution on the practice database. The task does not fix a sort order, so your rows may come back in a different order.

What you practise

  • Working with dates in SQLite: strftime, julianday and DATE
  • Reading the previous row's value with LAG()
  • Deriving a new column from an expression and naming it with an alias

Hint and approach

Try the challenge first. Open these only when you need them.

Show the hint

LAG hire_date

Show the step-by-step approach

How the model solution is built, in the order the database evaluates it:

  1. Read from the employees table.
  2. Fetch hire_date from the previous row with LAG(), ordered by hire_date. Where there is no such row the value is NULL.
  3. Combine those values into the output column: julianday(hire_date) - julianday(LAG(hire_date) OVER (ORDER BY hire_date)).

Model solution

Checking your session…

What to watch for

  • LAG(). LAG() returns NULL for the first row of each partition, and any arithmetic with that NULL is NULL too. Supply a default as the third argument if you need a number.
  • Date functions. These date functions are SQLite syntax. MySQL uses DATE_FORMAT and DATEDIFF, PostgreSQL uses TO_CHAR, EXTRACT and date subtraction.
  • Calculated columns. Dividing one integer by another truncates the result in SQLite. Multiply one side by 1.0 to get decimals.
Solve This SQL Challenge

Keep learning