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_
This is a Pro chapter
Sign in, then upgrade to Pro or Power to unlock this and the full Databases Mastery library.
How do you write a SQL query to detect gaps in a sequential ID sequence?