Skip to content
We areTOP 1%

Consecutive Numbers

MediumLeetCodeSQL: Window Functions
Solve on LeetCode(opens in a new tab)
Track your progress
First attempt
Re-solve after a few days
Final pass before interviews
Hint and exampleShow

Compare each row with the following rows using LEAD (or self joins on consecutive ids) and keep the values that repeat in all of them.

Example: readings(id, status) — statuses seen at least 3 times in a row

id | status
1  | ok
2  | down
3  | down
4  | down
5  | ok
SELECT DISTINCT status
FROM (
  SELECT status,
         LEAD(status, 1) OVER (ORDER BY id) AS next1,
         LEAD(status, 2) OVER (ORDER BY id) AS next2
  FROM readings
) t
WHERE status = next1 AND status = next2;   -- returns down

More in SQL: Window Functions

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account