Simple case: only first gap
You can do that with:
SELECT
MIN(seq)
FROM
(SELECT
sequence,
@seq:=@seq+1 AS seq
FROM
t CROSS JOIN (SELECT @seq:=0) AS init) AS gap
WHERE
sequence!=seq
-here field sequence
is pointing to your column, where you're looking for gap. See fiddle demo
Now, common case.
You can not use just JOIN
or something like this, since size of your table may be lesser than possible gap in it. Imagine the situation, when your table is filled with only minimum and maximum value. For example, 1
and 10
- and you want to get all rows, so result will be sequence 1, 2, ... , 10
. No matter how you will JOIN
your table with itself, you will only get two rows - because only those two exist in your table. UNION
is also not an option - since if we'll build that for 10
, in common case that can be 100
, 1000
, e t.c. So for common case you have to create sequence table and fill it with values from MIN(sequence)
and MAX(sequence)
- and then, using LEFT JOIN, do like:
SELECT
full_table.sequence
FROM
full_table
LEFT JOIN t
ON full_table.sequence=t.sequence
WHERE
t.sequence IS NULL