Dev Helpers

SQL / Window frames

Compare to a neighbouring job

Dev Helpers · February 26, 2026

Neighbour comparisons require a stable ordering. An ID tie or timestamp tie can change which record counts as the neighbour.

Worked example

CREATE TABLE queues(name TEXT PRIMARY KEY, owner TEXT);
INSERT INTO queues VALUES
  ('build','platform'), ('assets','design'), ('reports','platform'), ('idle','ops');
CREATE TABLE jobs(id INTEGER PRIMARY KEY, name TEXT, queue TEXT, status TEXT, ms INTEGER, created TEXT);
INSERT INTO jobs VALUES
  (1,'compile-api','build','done',300,'2026-01-01 08:00'),
  (2,'test-api','build','done',500,'2026-01-01 09:00'),
  (3,'compile-css','assets','running',200,'2026-01-02 08:00'),
  (4,'test-css','assets','queued',NULL,'2026-01-02 09:00'),
  (5,'report','reports','done',100,'2026-01-03 10:00'),
  (6,'publish','build','queued',NULL,'2026-01-03 11:00');

SELECT id,ms-lag(ms) OVER(ORDER BY id) AS delta FROM jobs;

Result

[
  {
    "id": 1,
    "delta": null
  },
  {
    "id": 2,
    "delta": 200
  },
  {
    "id": 3,
    "delta": -300
  },
  {
    "id": 4,
    "delta": null
  },
  {
    "id": 5,
    "delta": null
  },
  {
    "id": 6,
    "delta": null
  }
]

Implementation notes

Filtering before a window is evaluated can remove the neighbour you expected to compare. Perform the comparison in the intended population first.

Try it yourself

Insert a pair with the same sort key and add a tie-breaker.

Open the SQL example →

Editorial date February 26, 2026 · Published December 6, 2026

Related articles

Compare two literal lists

Set operations compare rows under SQL's rules for duplicates. Check whether the result represents membership or the number of occurrences.

Count jobs per active day

Grouping timestamps by day produces counts only for days present in the data. A continuous chart may need a calendar series as well.