While reading this page, I stumbled upon a trick (by Tom Kyte) to generate an alphanumeric character string of any length using the Oracle SQL function RPAD. The emphasis here is on the length of the string, not its content. Let’s say you want to generate a 10 character string, you can easily do it like this:
scott@EDDEV> select
2 rpad('&&first_string',&&total_length, '&&pad_with_string')
3 from dual;
Enter value for first_string: a
Enter value for total_length: 10
Enter value for pad_with_string: z
old 2: rpad('&&first_string',&&total_length, '&&pad_with_string')
new 2: rpad('a',10, 'z')
RPAD('A',1
----------
azzzzzzzzz
To generate a 15 character length string:
scott@EDDEV> define total_length=15
scott@EDDEV> /
old 2: rpad('&&first_string',&&total_length, '&&pad_with_string')
new 2: rpad('a',15, 'z')
RPAD('A',15,'Z'
---------------
azzzzzzzzzzzzzz
You get the picture. first_string and pad_with_string can be any alphanumeric character(s), total_length can be any integer. If the length of the first_string is greater than the total_length, the function will be equivalent to SUBSTR. For example:
scott@EDDEV> define first_string=hello world
scott@EDDEV> define total_length=4
scott@EDDEV> /
old 2: rpad('&&first_string',&&total_length, '&&pad_with_string')
new 2: rpad('hello',4, 'z')
RPAD
----
hell
scott@EDDEV> select substr('hello world',1,4) from dual;
SUBS
----
hell
Note that LPAD works the same way as RPAD, but instead of padding to the right, it pads to the left:
scott@EDDEV> define first_string=a
scott@EDDEV> define total_length=10
scott@EDDEV> define pad_with_string=z
scott@EDDEV> select
2 lpad('&&first_string',&&total_length, '&&pad_with_string')
3 from dual;
old 2: lpad('&&first_string',&&total_length, '&&pad_with_string')
new 2: lpad('a',10, 'z')
LPAD('A',1
----------
zzzzzzzzza
This usage of RPAD and LPAD comes in handy when you want to test your programs with character input values having different lengths.
Possibly related:
- More on Generating Strings
- Triggers and Constraints
- Random string generator
- Strong Encryption in ColdFusion MX 7
- The Easy Way to Generate an RSS Feed from Your Forum Posts
Tagged dbms_random, rpad | Post a Comment


















It’s always these types of things that trouble me. Good show!
October 18th, 2005, at 7:24 am #Have you tried
The second argument specifies the length of the string. The first one specifies some string options, but I haven’t researched that any deeper.
/Kristian
October 25th, 2005, at 7:50 am #Kristian, your query works as well. Thanks for this great tip.
October 25th, 2005, at 4:49 pm #[…] A while ago I blogged about how you could use the rpad function to generate a string of any length. Kristian suggested another way to do it, using the dbms_random.string function. In this post, I will write about what I have noticed when using the two approaches. […]
December 6th, 2005, at 1:10 pm #[…] Read more about generating strings here and here. […]
March 6th, 2006, at 10:04 pm #