snipt

Ctrl+h for KB shortcuts

MySQL

MySQL get missing IDs from table

1
2
3
4
5
6
7
8
SELECT a.id+1 AS start, MIN(b.id) - 1 AS end
FROM testtable AS a, testtable AS b
WHERE a.id < b.id
GROUP BY a.id
HAVING start < MIN(b.id)

-- http://stackoverflow.com/questions/12325132/mysql-get-missing-ids-from-table
-- http://www.codediesel.com/mysql/sequence-gaps-in-mysql/
https://snipt.net/embed/21272b09b0b86923c0a2890e893b1d9a/
/raw/21272b09b0b86923c0a2890e893b1d9a/
21272b09b0b86923c0a2890e893b1d9a
mysql
MySQL
8
2019-08-25T11:32:31
True
False
False
Nov 20, 2013 at 11:49 AM
/api/public/snipt/95552/
mysql-get-missing-ids-from-table
<table class="highlighttable"><tr><td class="linenos"><div class="linenodiv"><pre><a href="#L-1">1</a> <a href="#L-2">2</a> <a href="#L-3">3</a> <a href="#L-4">4</a> <a href="#L-5">5</a> <a href="#L-6">6</a> <a href="#L-7">7</a> <a href="#L-8">8</a></pre></div></td><td class="code"><div class="highlight"><pre><span></span><span id="L-1"><a name="L-1"></a><span class="k">SELECT</span> <span class="n">a</span><span class="p">.</span><span class="n">id</span><span class="o">+</span><span class="mi">1</span> <span class="k">AS</span> <span class="n">start</span><span class="p">,</span> <span class="nf">MIN</span><span class="p">(</span><span class="n">b</span><span class="p">.</span><span class="n">id</span><span class="p">)</span> <span class="o">-</span> <span class="mi">1</span> <span class="k">AS</span> <span class="n">end</span> </span><span id="L-2"><a name="L-2"></a><span class="k">FROM</span> <span class="n">testtable</span> <span class="k">AS</span> <span class="n">a</span><span class="p">,</span> <span class="n">testtable</span> <span class="k">AS</span> <span class="n">b</span> </span><span id="L-3"><a name="L-3"></a><span class="k">WHERE</span> <span class="n">a</span><span class="p">.</span><span class="n">id</span> <span class="o">&lt;</span> <span class="n">b</span><span class="p">.</span><span class="n">id</span> </span><span id="L-4"><a name="L-4"></a><span class="k">GROUP</span> <span class="k">BY</span> <span class="n">a</span><span class="p">.</span><span class="n">id</span> </span><span id="L-5"><a name="L-5"></a><span class="k">HAVING</span> <span class="n">start</span> <span class="o">&lt;</span> <span class="nf">MIN</span><span class="p">(</span><span class="n">b</span><span class="p">.</span><span class="n">id</span><span class="p">)</span> </span><span id="L-6"><a name="L-6"></a> </span><span id="L-7"><a name="L-7"></a><span class="c1">-- http://stackoverflow.com/questions/12325132/mysql-get-missing-ids-from-table</span> </span><span id="L-8"><a name="L-8"></a><span class="c1">-- http://www.codediesel.com/mysql/sequence-gaps-in-mysql/</span> </span></pre></div> </td></tr></table>
mysql