Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to write query? 2

Status
Not open for further replies.

Gjj

Programmer
Sep 23, 2005
15
YU
I have table

Number Some data
1 x
3 y
4 s
5 x

I would like to find smallest number starting from 1 which is not in the table.

In this case that would be 2.
Does somebody have idea how to write query?
 
A couple of suggestions:

Code:
select min(num)+1
from test_num t1
where not exists
(select 1 from test_num t2
where t2.num + 1= t1.num)

Code:
select min(rnum) from
(select rownum as rnum from all_objects)
where rnum not in (select num from test_num)
 
another idea:
Code:
select min(x) from
(
select 1 as x from dual
UNION
select num+1 from table
MINUS
select num from table)
/

Dagon:
I think your first suggestion will not work, if 1 is not in the table.

regards
 
Yes, I was aware of that, which is why I gave an alternative. Actually, you could probably do the second example more simply using something like:

Code:
select min(rnum) from
(select num, rownum as rnum from test_num)
where num <> rnum
 
Dagon,

I disagree with your change of your second example.
You are making assumptions about the order how data is stored.
And yes, there is a workaround. But this will not make the example simple.
[wink]

Gjj,

glad it helped, thanks

regards
 
Fair point. Change it to:


Code:
select min(rnum) from
(select num, rownum as rnum from 
(select * from test_num order by num))
where num <> rnum
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top