Finding Gaps in Sequences with SQL
📖 Scenario: You work for a library that tracks book IDs assigned sequentially. Sometimes, IDs are missing due to errors or removals. You want to find these missing book IDs to fix the records.
🎯 Goal: Build an SQL query that finds missing numbers (gaps) in a sequence of book IDs stored in a table.
📋 What You'll Learn
Create a table called
books with a column book_id containing these exact values: 1, 2, 3, 5, 6, 8, 9, 10Create a variable or CTE called
max_id that stores the maximum book_id from the books tableGenerate a sequence of numbers from 1 to
max_id using a recursive CTE called sequenceWrite a query that selects numbers from
sequence that are not present in books to find missing book_ids💡 Why This Matters
🌍 Real World
Finding missing IDs or sequence gaps is common in inventory, order tracking, or any system that uses sequential numbering.
💼 Career
Database developers and analysts often need to detect missing records or gaps to ensure data integrity and correct errors.
Progress0 / 4 steps