SQL Boy
TutorialsPlayground

Format & Validate

SQL FormatterSQL MinifierSyntax Validator

Convert

JSON to SQLCSV to SQLSQL to JSONRegex to SQLExcel to SQLSQL Dialect Convertersoon

Visualize

ER Diagram GeneratorSQL Schema Diff

Generate

SQL Mock Data Generator

Analyze

SQL Query ExplainerSQL Query Analyzer

Workflow hubs

FormattingConversionSchemaAnalysis
View all tools
Daily ChallengeInterviewsCheat SheetBlog

© 2026 SQL Boy. Built for developers.

ContactPrivacyTermsAI Usage PolicyEditorial StandardsAboutRSS Feed

New conversation

What can I help with?

Ask about this page, get a hint on a challenge, or explore SQL concepts.

I know what's on this page and can give answers grounded in SQL Boy content.

Current page

Consecutive Numbers

/challenges/consecutive-numbers

Usage status will load after login
SQL Boy
TutorialsPlayground

Format & Validate

SQL FormatterSQL MinifierSyntax Validator

Convert

JSON to SQLCSV to SQLSQL to JSONRegex to SQLExcel to SQLSQL Dialect Convertersoon

Visualize

ER Diagram GeneratorSQL Schema Diff

Generate

SQL Mock Data Generator

Analyze

SQL Query ExplainerSQL Query Analyzer

Workflow hubs

FormattingConversionSchemaAnalysis
View all tools
Daily ChallengeInterviewsCheat SheetBlog
SQL Challenges/Consecutive Numbers
Challenge DetailHardReviewed 2026-04-20

Consecutive Numbers

Find numbers that appear at least 3 times consecutively in the logs table.

JoinWindow Functions

This challenge now meets the current minimum standard for sitemap inclusion and independent indexing.

2025-12-13Hard

Consecutive Numbers

Find numbers that appear at least 3 times consecutively in the logs table.

Available Tables:
SQL Editor
Loading...

What This Challenge Is Testing

This is a row-sequence problem, not just a counting problem. Similar logic shows up in fraud detection, uptime monitoring, anomaly streaks, and event-stream analysis where you care about repeated behavior across adjacent records rather than total frequency.

Topic Tags

Window FunctionsAnalytics

Schema At A Glance

logs
idnum

Solution Approaches

01

Self join three adjacent rows

SELECT DISTINCT l1.num AS ConsecutiveNums
FROM logs l1
JOIN logs l2
  ON l1.id = l2.id - 1
JOIN logs l3
  ON l2.id = l3.id - 1
WHERE l1.num = l2.num
  AND l2.num = l3.num

This is the classic solution. It models the streak directly by lining up three neighboring rows and checking whether all three contain the same number.

02

Use LAG and LEAD to inspect neighbors

WITH numbered AS (
  SELECT
    id,
    num,
    LAG(num) OVER (ORDER BY id) AS prev_num,
    LEAD(num) OVER (ORDER BY id) AS next_num
  FROM logs
)
SELECT DISTINCT num AS ConsecutiveNums
FROM numbered
WHERE num = prev_num
  AND num = next_num

The window-function version is easier to generalize to longer streak analysis. It centers each row and checks whether the previous and next values match the current value.

Common Pitfalls

Do not solve this with `GROUP BY num HAVING COUNT(*) >= 3`. That only proves a number appears three times somewhere in the table, not that the appearances are consecutive. Another trap is assuming ID gaps do not matter when the sequence condition depends on adjacent rows.

Frequently Asked Questions

Why is this not just an aggregation problem?

Because the question is about ordering and adjacency. A number can appear many times overall but still never form a run of three consecutive rows.

When is the window-function version better?

Use LAG and LEAD when you expect follow-up questions about longer streaks, breakpoints, or more complex sequence analysis. It scales better conceptually than adding more self joins.

Concept Guides

Use these guides when you want the fuller explanation behind the SQL pattern this challenge is testing.

Understanding SQL Window Functions: A Visual Guide

Master ROW_NUMBER, RANK, and running totals with interactive visualizations. See exactly how window functions process your data row by row.

Solving the Gaps and Islands Problem in SQL

Master one of the most famous SQL interview questions: identifying consecutive ranges (islands) and missing sequences (gaps) in your data.

Mastering SQL Self Joins: A Complete Guide with Interactive Examples

Stop being confused by joins on the same table. Learn how to master Self Joins for organizational hierarchies, sequential data comparison, and more.

Topic Hubs

If this problem exposed a deeper weakness, use a topic hub to move through a curated cluster instead of random article hopping.

Advanced SQL

Advanced query patterns

Use this path when you are moving beyond beginner SELECT queries into CTEs, window functions, and conditional logic.

Analytics

Analytics SQL and business metrics

A practical cluster for cohorts, funnels, customer value, and the kinds of reporting questions teams actually ask every week.

Practice Path

If you want the rotating practice flow, open this same question from the daily stream. If you want interview-style packaging, continue into the interview pool after this rep.

Back to ChallengesOpen In DailyBrowse Interviews

Related Challenges

Rising TemperatureMedium

Compare each weather row with the previous day and return only the IDs where temperature increased day over day.

Rank ScoresMedium

Assign tied scores the same rank while keeping the next rank consecutive with no gaps.

Last Person to Fit in the BusMedium

Use a running total to find the last passenger whose cumulative weight still stays under the bus limit.

© 2026 SQL Boy. Built for developers.

ContactPrivacyTermsAI Usage PolicyEditorial StandardsAboutRSS Feed