SELECT min(table3.id3 ) FROM ( select table1.id as id3 from ( select id from sheet1 ) as table1 left outer join ( select id + 1 as id2 from table ) as table2 on table1.id = table2.id2 where table2.id2 is null union select 1 as id3 from ( select count(id) from sheet1 ) ). AS table3, ( select min(table4.id4 ) as id5 from ( select table1.id as id4 from ( select id from table ) as table1 left outer join ( select id + 1 as id2 from table ) as table2 on table1.id = table2.id2 where table2.id2 is null ) as table4 ). AS table5 WHERE table3.id3 <> table5.id5