Question
Write a SQL query to find all numbers that appear at least three times consecutively in the Logs table.
Return the result in any order.
Table Schema
Solution
SELECT DISTINCT num AS ConsecutiveNums FROM ( SELECT num, LAG(num, 1) OVER (ORDER BY id) AS prev1, LAG(num, 2) OVER (ORDER BY id) AS prev2 FROM Logs ) t WHERE num = prev1 AND num = prev2;
Explanation
-
LAG(num, 1) : looks at the previous row’s number.
-
LAG(num, 2): looks at the two rows before.
-
If num = prev1 = prev2, that means the number appeared 3 times consecutively.
-
DISTINCT avoids duplicates.
![]()
