Back

Advanced · 18 min

Comparing neighboring rows

Use LAG to compare a row with an earlier row in its partition.

Sample database

CREATE TABLE groups (id INTEGER PRIMARY KEY, label TEXT NOT NULL);
CREATE TABLE members (id INTEGER PRIMARY KEY, name TEXT NOT NULL, city TEXT, group_id INTEGER REFERENCES groups(id));
CREATE TABLE sessions (id INTEGER PRIMARY KEY, member_id INTEGER NOT NULL REFERENCES members(id), topic TEXT NOT NULL, minutes INTEGER NOT NULL CHECK(minutes > 0), completed INTEGER NOT NULL CHECK(completed IN (0, 1)), day TEXT NOT NULL);
INSERT INTO groups VALUES (1, 'Morning'), (2, 'Evening');
INSERT INTO members VALUES (1, 'Ada', 'Oslo', 1), (2, 'Bo', 'Rome', 1), (3, 'Cy', NULL, 2), (4, 'Dee', 'Oslo', 2);
INSERT INTO sessions VALUES
  (1, 1, 'Travel', 20, 1, '2026-01-01'),
  (2, 1, 'Food', 10, 0, '2026-01-02'),
  (3, 2, 'Travel', 30, 1, '2026-01-01'),
  (4, 2, 'Music', 15, 1, '2026-01-03'),
  (5, 3, 'Music', 25, 0, '2026-01-02'),
  (6, 3, 'Travel', 15, 1, '2026-01-04');

Read the previous value

LAG reads a value from an earlier ordered row without a self-join. It returns NULL when there is no earlier row unless a default is supplied. The ordering must represent the sequence you mean to compare.

SELECT member_id, id, LAG(minutes) OVER (PARTITION BY member_id ORDER BY day, id) AS previous_minutes FROM sessions ORDER BY member_id, day, id;

Output

member_id | id | previous_minutes
1 | 1 | NULL
1 | 2 | 20
2 | 3 | NULL
2 | 4 | 30
3 | 5 | NULL
3 | 6 | 25

Calculate a change

Subtracting a previous value produces a per-row change. A first-row NULL can be meaningful: no comparison exists. Do not automatically turn it into zero unless the report explicitly needs that interpretation.

SELECT member_id, id, minutes - LAG(minutes) OVER (PARTITION BY member_id ORDER BY day, id) AS change FROM sessions ORDER BY member_id, day, id;

Output

member_id | id | change
1 | 1 | NULL
1 | 2 | -10
2 | 3 | NULL
2 | 4 | -15
3 | 5 | NULL
3 | 6 | -10

Put it into practice

  1. Read the sample tables and predict the result before running the query.
  2. Solve the task, compare the returned rows, and explain why the solution works.

Try it yourself

Code runs on this device. When you are signed in, drafts sync to your account.

Run queries on a fresh sample database. Table changes last for this run only; your query draft is saved separately. Results show column names followed by rows. NULL means a missing value.

Apply what you learned

Return each session and the change from that member previous session duration. Keep NULL when there is no previous session.

Show solution
SELECT member_id, id, minutes - LAG(minutes) OVER (PARTITION BY member_id ORDER BY day, id) AS change FROM sessions ORDER BY member_id, day, id;

The partition prevents one member duration from being compared with another member activity.

Practice