Random function/Sequence like field

Posted on 2006-05-06
Last Modified: 2012-05-05

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!
Question by:windows_programing
    LVL 15

    Assisted Solution

    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;)
    LVL 22

    Accepted Solution

    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)

    Author Comment


    I like earthman2's function that allows me to specify the number of random characters.

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Maximize Your Threat Intelligence Reporting

    Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

    Best database to use for Maps is PostgreSQL. This is an open source database. Comes as a package with most Linux OS. For more info visit the following site: ( This requires some add-o…
    Many developers have database experience, but are new to PostgreSQL. It has some truly inspiring capabilities. I have several years' experience with Microsoft's SQL Server. When I began working with MySQL, I wanted a quick-reference to MySQL (htt…
    Steps to create a PostgreSQL RDS instance in the Amazon cloud. We will cover some of the default settings and show how to connect to the instance once it is up and running.
    This video discusses moving either the default database or any database to a new volume.

    760 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    15 Experts available now in Live!

    Get 1:1 Help Now