intermediateTop 30 Scenario-Based Questions
How do you write a SQL query to detect gaps in a sequential ID sequence?
SELECT generate_series + 1 AS missing_id FROM generate_series(1, (SELECT MAX(id) FROM orders) - 1) gs WHERE gs + 1 NOT IN (SELECT id FROM orders); Or more efficiently: SELECT s.id + 1 AS gap_start FROM orders s WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.id = s.id + 1) AND s.id < (SELECT MAX(id) FROM orders) ORDER BY gap_start; Or with LAG: SELECT prev_id + 1 AS gap_start, curr_id - 1 AS gap_
Ready to master this question?
Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response