Interview Questions/SQL/Consecutive Numbers

Consecutive Numbers

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Description

You are given a Logs table that records numbers against sequential IDs. Write a SQL query to find all numbers that appear at least three times consecutively (i.e., in three consecutive rows ordered by id). Return the result in any order with no duplicates.

Database Schema

Logs

Column NameExample Value
id1
num1

Example

Logs

idnum
11
21
31
42
51
62
72

Output

ConsecutiveNums
1

Explanation:

1 appears at ids 1, 2, 3 consecutively. 2 never appears three times in a row.

Approach hint

Start with a simple approach, explain the trade-off, then move toward a cleaner or more scalable solution.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

SQL Editor
Loading...

Logs

idnum
11
21
31
42
51
62
72

Output

ConsecutiveNums
1