Skip to Main Content
  • Questions
  • Unique random alpha numeric in specific format

Breadcrumb

Question and Answer

Chris Saxon

Thanks for the question, vid.

Asked: July 11, 2019 - 2:03 pm UTC

Last updated: July 11, 2019 - 4:00 pm UTC

Version: Oracle 10

Viewed 1000+ times

You Asked

Hi, my use-case is to generate a unique random alpha numeric in specific format as below. Can you please help?

Required Format: ANNNNNNNN (must start with random alpha char followed by 8 random digits)

and Chris said...

One way is a to wrap a sequence in calls to dbms_random to generate a letter and numbers. Padding out the sequence values with zeros as needed:

create sequence s;

select dbms_random.string ( 'U', 1 ) ||
       lpad ( s.nextval, 7, '0' ) ||
       round ( dbms_random.value ( 0, 9 ) ) val 
from   dual
connect by level <= 10;

VAL         
N00000018    
Q00000029    
Z00000038    
D00000048    
L00000051    
N00000064    
F00000072    
V00000082    
M00000092    
X00000103 


Note this only guarantees 10 million unique values. Once your sequence hits this value, you could start generating duplicates. I'm not aware of a good way to solve this...

Is this answer out of date? If it is, please let us know via a Comment

More to Explore

Design

New to good database design? Check out Chris Saxon's full fundamentals class.