Bird
Raised Fist0
SQLquery~20 mins

Finding gaps in sequences in SQL - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Sequence Gap Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ query_result
intermediate
2:00remaining
Find missing invoice numbers in a sequence

Given a table Invoices with a column InvoiceNumber containing sequential invoice numbers, which query correctly finds all missing invoice numbers between the minimum and maximum?

SQL
CREATE TABLE Invoices (InvoiceNumber INT);
INSERT INTO Invoices VALUES (1001), (1002), (1004), (1005), (1007);
ASELECT InvoiceNumber AS MissingNumber FROM Invoices WHERE InvoiceNumber NOT IN (SELECT InvoiceNumber + 1 FROM Invoices);
BSELECT InvoiceNumber - 1 AS MissingNumber FROM Invoices WHERE InvoiceNumber - 1 NOT IN (SELECT InvoiceNumber FROM Invoices);
CSELECT InvoiceNumber + 2 AS MissingNumber FROM Invoices WHERE InvoiceNumber + 2 NOT IN (SELECT InvoiceNumber FROM Invoices);
DSELECT InvoiceNumber + 1 AS MissingNumber FROM Invoices WHERE InvoiceNumber + 1 NOT IN (SELECT InvoiceNumber FROM Invoices);
Attempts:
2 left
💡 Hint

Think about checking the next number after each existing invoice to see if it is missing.

📝 Syntax
intermediate
2:00remaining
Identify the syntax error in gap detection query

Which of the following SQL queries will cause a syntax error when trying to find missing IDs in a sequence?

SQL
CREATE TABLE Items (ID INT);
INSERT INTO Items VALUES (1), (2), (4), (5);
ASELECT ID + 1 AS MissingID FROM Items WHERE ID + 1 NOT IN (SELECT ID FROM Items);
BSELECT ID + 1 AS MissingID FROM Items WHERE ID + 1 NOT EXISTS (SELECT ID FROM Items);
CSELECT ID + 1 AS MissingID FROM Items WHERE NOT EXISTS (SELECT 1 FROM Items WHERE ID = Items.ID + 1);
D;)smetI MORF DI TCELES( NI TON 1 + DI EREHW smetI MORF DIgnissiM SA 1 + DI TCELES
Attempts:
2 left
💡 Hint

Check the use of NOT EXISTS and NOT IN clauses.

❓ optimization
advanced
2:00remaining
Optimize gap detection for large sequences

You have a large table Orders with millions of sequential OrderID values. Which query is the most efficient to find missing OrderID values?

ASELECT o1.OrderID + 1 AS MissingID FROM Orders o1 LEFT JOIN Orders o2 ON o1.OrderID + 1 = o2.OrderID WHERE o2.OrderID IS NULL;
B
WITH Numbers AS (SELECT generate_series(MIN(OrderID), MAX(OrderID)) AS num FROM Orders)
SELECT num AS MissingID FROM Numbers WHERE num NOT IN (SELECT OrderID FROM Orders);
CSELECT OrderID + 1 AS MissingID FROM Orders WHERE OrderID + 1 NOT IN (SELECT OrderID FROM Orders);
DSELECT DISTINCT OrderID FROM Orders WHERE OrderID NOT IN (SELECT OrderID + 1 FROM Orders);
Attempts:
2 left
💡 Hint

Consider join operations versus subqueries for performance on large data.

🧠 Conceptual
advanced
2:00remaining
Understanding gap detection logic

Why does the query SELECT ID + 1 FROM Table WHERE ID + 1 NOT IN (SELECT ID FROM Table) correctly find missing numbers in a sequence?

ABecause it checks for each ID if the next number is missing by verifying it is not present in the table.
BBecause it selects all IDs and adds 1 to them regardless of presence in the table.
CBecause it finds IDs that are duplicated in the table.
DBecause it returns all IDs that are present in the table plus one.
Attempts:
2 left
💡 Hint

Think about what ID + 1 NOT IN (SELECT ID) means logically.

🔧 Debug
expert
3:00remaining
Debugging incorrect gap detection query

The following query is intended to find missing sequence numbers in SeqTable but returns no results even though gaps exist. What is the reason?

SELECT seq + 1 AS MissingSeq FROM SeqTable WHERE seq + 1 NOT IN (SELECT seq FROM SeqTable);

Table data: seq = 1, 2, 4, 5

AThe subquery uses the wrong column name causing no matches.
BThe query syntax is invalid and causes an error.
CThe query misses the last gap because it only checks seq + 1 for existing seq values, so it cannot find gaps after the max value.
DThe query should use <code>NOT EXISTS</code> instead of <code>NOT IN</code> to work correctly.
Attempts:
2 left
💡 Hint

Consider how the query checks for missing numbers and what happens at the sequence boundaries.

Practice

(1/5)
1. What is the main purpose of using the LEAD() function when finding gaps in a sequence of numbers in SQL?
easy
A. To find the maximum number in the sequence
B. To compare each number with the next number in the sequence
C. To sum all numbers in the sequence
D. To sort the numbers in descending order

Solution

  1. Step 1: Understand the role of LEAD()

    The LEAD() function allows you to look at the next row's value in the current row's context.
  2. Step 2: Identify how LEAD() helps find gaps

    By comparing the current number with the next number, you can detect if there is a gap (difference greater than 1).
  3. Final Answer:

    To compare each number with the next number in the sequence -> Option B
  4. Quick Check:

    LEAD() compares current and next values [OK]
Hint: Use LEAD() to peek at the next number in sequence [OK]
Common Mistakes:
  • Thinking LEAD() sums values
  • Confusing LEAD() with aggregate functions
  • Using LEAD() to sort data
2. Which of the following SQL snippets correctly uses LEAD() to find gaps in a sequence column named num in table numbers?
easy
A. SELECT num, LEAD(num) AS next_num FROM numbers;
B. SELECT num, LEAD(num) FROM numbers ORDER BY num;
C. SELECT num, LEAD(num) OVER (ORDER BY num) AS next_num FROM numbers;
D. SELECT num, LEAD(num) OVER () AS next_num FROM numbers;

Solution

  1. Step 1: Check LEAD() syntax

    The correct syntax requires LEAD(column) OVER (ORDER BY column) to define the order for the window function.
  2. Step 2: Identify the correct option

    SELECT num, LEAD(num) OVER (ORDER BY num) AS next_num FROM numbers; uses LEAD(num) OVER (ORDER BY num), which is the correct form to get the next number in order.
  3. Final Answer:

    SELECT num, LEAD(num) OVER (ORDER BY num) AS next_num FROM numbers; -> Option C
  4. Quick Check:

    LEAD() needs OVER with ORDER BY [OK]
Hint: Always include OVER(ORDER BY column) with LEAD() [OK]
Common Mistakes:
  • Omitting OVER clause
  • Not specifying ORDER BY inside OVER
  • Using LEAD() without alias
3. Given the table numbers with column num containing values (1, 2, 4, 5, 7), what will the following query return?
SELECT num, LEAD(num) OVER (ORDER BY num) AS next_num FROM numbers;
medium
A. [{num:1, next_num:2}, {num:2, next_num:4}, {num:4, next_num:5}, {num:5, next_num:7}, {num:7, next_num:null}]
B. [{num:1, next_num:1}, {num:2, next_num:2}, {num:4, next_num:4}, {num:5, next_num:5}, {num:7, next_num:7}]
C. [{num:1, next_num:3}, {num:2, next_num:4}, {num:4, next_num:6}, {num:5, next_num:7}, {num:7, next_num:null}]
D. [{num:1, next_num:null}, {num:2, next_num:null}, {num:4, next_num:null}, {num:5, next_num:null}, {num:7, next_num:null}]

Solution

  1. Step 1: Understand LEAD() output

    LEAD(num) returns the next row's num value ordered by num. So each row shows its own num and the next number.
  2. Step 2: Apply to given data

    For values 1,2,4,5,7:
    1's next is 2
    2's next is 4
    4's next is 5
    5's next is 7
    7 has no next, so null
  3. Final Answer:

    [{num:1, next_num:2}, {num:2, next_num:4}, {num:4, next_num:5}, {num:5, next_num:7}, {num:7, next_num:null}] -> Option A
  4. Quick Check:

    LEAD() shifts values down by one [OK]
Hint: LEAD() shows next row's value or null if none [OK]
Common Mistakes:
  • Assuming LEAD() repeats current value
  • Expecting gaps filled automatically
  • Confusing LEAD() with LAG()
4. The following query is intended to find gaps in the num sequence but returns no rows:
SELECT num FROM numbers WHERE LEAD(num) OVER (ORDER BY num) - num > 1;

What is the error?
medium
A. You cannot use window functions directly in WHERE clause
B. The ORDER BY inside LEAD() is missing
C. The subtraction operator is invalid here
D. LEAD() requires a GROUP BY clause

Solution

  1. Step 1: Understand window function restrictions

    Window functions like LEAD() cannot be used directly in the WHERE clause because WHERE filters rows before window functions are applied.
  2. Step 2: Correct approach

    Use a subquery or CTE to compute LEAD() first, then filter in an outer query.
  3. Final Answer:

    You cannot use window functions directly in WHERE clause -> Option A
  4. Quick Check:

    Window functions not allowed in WHERE [OK]
Hint: Use subquery or CTE to filter on window function results [OK]
Common Mistakes:
  • Trying to filter window function in WHERE
  • Missing OVER clause
  • Expecting LEAD() to work like aggregate
5. You have a table orders with an integer column order_id that should be sequential but may have missing numbers. Which query correctly finds all missing order_id values between the minimum and maximum present?
hard
A. SELECT order_id FROM orders WHERE LEAD(order_id) - order_id > 1;
B. SELECT DISTINCT order_id + 1 FROM orders WHERE order_id + 1 NOT IN (SELECT order_id FROM orders);
C. SELECT order_id FROM orders WHERE order_id NOT IN (SELECT order_id FROM orders);
D. WITH seq AS (SELECT generate_series(MIN(order_id), MAX(order_id)) AS id FROM orders) SELECT id FROM seq LEFT JOIN orders ON seq.id = orders.order_id WHERE orders.order_id IS NULL;

Solution

  1. Step 1: Generate full sequence range

    Use generate_series from minimum to maximum order_id to create all possible IDs.
  2. Step 2: Find missing IDs by left join

    Left join this sequence to existing orders and select IDs where no matching order exists (NULL in orders).
  3. Final Answer:

    WITH seq AS (SELECT generate_series(MIN(order_id), MAX(order_id)) AS id FROM orders) SELECT id FROM seq LEFT JOIN orders ON seq.id = orders.order_id WHERE orders.order_id IS NULL; -> Option D
  4. Quick Check:

    Generate full range, then find missing with LEFT JOIN [OK]
Hint: Generate full range then find missing with LEFT JOIN [OK]
Common Mistakes:
  • Using LEAD() alone misses multiple gaps
  • Incorrect NOT IN subquery logic
  • Assuming order_id + 1 always missing
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard