Random function/Sequence like field


I am trying to figure out the best way to create a field that contains a randomly generated string.  I'm currently using a sequence as a test for this field.  I'd like to make this a bit more secure by adding a randomly generated 16 character string.  I'm not sure how I would do this in plpgsql language. Any suggestions ?  Thanks!
Who is Participating?
earth man2Connect With a Mentor Commented:
create or replace function random_string( size in integer ) returns text as $$
  s  text := '';
  idx int := 1;

  while (  idx < size ) loop

    s := s || chr( floor( random() * ( ascii('z') - ascii('a') ) + ascii('a') )::int );

    idx := idx + 1;

  end loop;

  return s;
$$ language plpgsql;

=> select random_string(10);
(1 row)
m1tk4Connect With a Mentor Commented:
using the random() funciton:

select  select chr((random()*25)::int+97)||chr((random()*25)::int+97) ;

for example will produce random 2-character strings using characters a (ASCII 97) to z (ASCII 122 ( = 97+25)). Just type it 14 times more to get a 16 characters;)
windows_programingAuthor Commented:

I like earthman2's function that allows me to specify the number of random characters.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.