Generate random String in PostgreSQL
Another solution that's pretty easy to read (perf should be reasonable, but no benchmarks were performed):
select substr(md5(random()::text), 0, 25);
Could be uppercased if you prefer:
select upper(substr(md5(random()::text), 0, 25));
Here is my contrib
postgres=# SELECT array_to_string(array(select substr('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789',((random()*(36-1)+1)::integer),1) from generate_series(1,50)),''); array_to_string ---------------------------------------------------- 4XOS6TQG5JORLF3D1RPXUWR2FQKON9HIXV0UGH0CQFT1LN5D4L(1 row)
It lets you specify the set of allowed characters and the length of the string.
This will give you a random word of length 15 consisting of the letters configured in the source values constant
select string_agg(substr(characters, (random() * length(characters) + 1)::integer, 1), '') as random_wordfrom (values('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789')) as symbols(characters) -- length of word join generate_series(1, 15) on 1 = 1
EDIT: to obtain multiple random words you can use the following:
with symbols(characters) as (VALUES ('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'))select string_agg(substr(characters, (random() * length(characters) + 1) :: INTEGER, 1), '')from symbolsjoin generate_series(1,8) as word(chr_idx) on 1 = 1 -- word lengthjoin generate_series(1,10000) as words(idx) on 1 = 1 -- # of wordsgroup by idx