I have a table like this:
create table thing (
id bigint primary key auto_increment,
code integer not null,
description varchar(100)
);
The table usually has consecutives codes but the user has the posibility of change the generates code for other more convenient for him, so he can break the chain. Also he can remove some thing
.
So, I'm trying to figure out how to get the first not used code.
For instance:
- If I have 1, 2, I want to get 3
- If I have 1, 2, 3, 50 and 51, I want to get 4.
I have thought in the next two queries which resolve my problem but none of them seems to be a good option.
The first one uses an exists
which I think it is inefficient since it has quadratic order.
select min(code)+1 from thing t
where not exists (select * from thing where code = t.code + 1);
The second is impossible to implement on Hibernate HQL queries since I am trying to use a strange join clause t1.code = t2.code - 1
select min(t1.code)+ 1
from thing t1 left join thing t2 on t1.code = t2.code - 1
where t2.id is null;