Consecutive Numbers SQL Challenge - MySQL Solution

1. Introduction

This blog post discusses how to identify sequences of consecutive numbers in a MySQL database. This kind of query can be useful in various data analysis scenarios where you need to find patterns or sequences in your data.


The task is to write a MySQL query that finds all numbers that appear at least three times consecutively in a given table.

Database Table:

Logs Table:
Id Num
1 100
2 100
3 100

3. MySQL Solution

SELECT DISTINCT l1.Num AS ConsecutiveNums
FROM Logs l1, Logs l2, Logs l3
WHERE l1.Id = l2.Id - 1 AND l2.Id = l3.Id - 1
AND l1.Num = l2.Num AND l2.Num = l3.Num;




1. The query uses a self-join on the Logs table three times to compare consecutive rows.

2. It checks if three consecutive rows (l1, l2, l3) have the same Num value.

3. The WHERE clause ensures that the Id values are sequential.

4. The query returns distinct numbers that appear consecutively at least three times.