Getting first 10 unused manual_sequence numbers

Viewed 145

I would like to find the first 10 unused manual sequence numbers from a range.

Please find my query below:

select X1.* From
    (Select Rownum seq_number From Dual Connect By Rownum <= 
         (Select LPAD(9,(UTC.DATA_PRECISION - UTC.DATA_SCALE),9) 
          From User_Tab_Columns UTC 
          where UTC.Table_Name = 'Table_Name' And UTC.Column_Name = 'seq_number')) X1,
Table_Name X2
Where X1.seq_number = X2.seq_number (+)
  And X2.Rowid is Null
  And Rownum <= 10

Although it gives the required output I am worried about the load caused [if any] because we will be using this query multiple times a day.

Please advise if there is a way to optimize this query.

Additional Info: On the Table_Name T2, there is a unique index defined on (seq_number)

Work Example:

create table TEMP_TABLE_NAME ( seq_number number(6))

insert into TEMP_TABLE_NAME 
select distinct trunc(dbms_random.VALUE(1,5000)) seq_number 
from dual
connect by rownum <= 1000


create unique index TEMP_TABLE_NAME_IDX on TEMP_TABLE_NAME(seq_Number)


SELECT T1.*
  FROM (    SELECT ROWNUM seq_number
              FROM DUAL
        CONNECT BY ROWNUM <=
                      (SELECT LPAD (9,(UTC.DATA_PRECISION - UTC.DATA_SCALE),9)
                         FROM User_Tab_Columns UTC
                        WHERE     UTC.Table_Name = 'TEMP_TABLE_NAME'
                              AND UTC.Column_Name = 'SEQ_NUMBER')) T1,
       TEMP_TABLE_NAME T2
 WHERE     T1.seq_number = T2.seq_number(+)
       AND T2.ROWID IS NULL
       AND ROWNUM <= 10

For me my query gave the below output. Randomly created numbers in the table included 7 & 8 so they were ignored. The point is to get first 10 unused numbers.

1
2
3
4
5
6
9
10
11
12
1 Answers
Related