Skip to content

Instantly share code, notes, and snippets.

@jvloo
Last active May 31, 2023 08:44
Show Gist options
  • Save jvloo/69682132b7caecf8b68b90deddd299c7 to your computer and use it in GitHub Desktop.
Save jvloo/69682132b7caecf8b68b90deddd299c7 to your computer and use it in GitHub Desktop.
How can we find gaps in sequential numbering in MySQL?
SELECT (t1.id + 1) as gap_starts_at,
(SELECT MIN(t3.id) -1 FROM arrc_vouchers t3 WHERE t3.id > t1.id) as gap_ends_at
FROM arrc_vouchers t1
WHERE NOT EXISTS (SELECT t2.id FROM arrc_vouchers t2 WHERE t2.id = t1.id + 1)
HAVING gap_ends_at IS NOT NULL
gap_starts_at - first id in current gap
gap_ends_at - last id in current gap
Reference: https://stackoverflow.com/a/6057665/6875460
## More efficient!
SELECT
CONCAT(z.expected, IF(z.got-1>z.expected, CONCAT(' thru ',z.got-1), '')) AS missing
FROM (
SELECT
@rownum:=@rownum+1 AS expected,
IF(@rownum=YourCol, 0, @rownum:=YourCol) AS got
FROM
(SELECT @rownum:=0) AS a
JOIN YourTable
ORDER BY YourCol
) AS z
WHERE z.got!=0;
Reference: https://stackoverflow.com/a/29736658/6875460
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment