Last active
May 31, 2023 08:44
-
-
Save jvloo/69682132b7caecf8b68b90deddd299c7 to your computer and use it in GitHub Desktop.
How can we find gaps in sequential numbering in MySQL?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## 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