?
Solved

Random function/Sequence like field

Posted on 2006-05-06
3
Medium Priority
?
374 Views
Last Modified: 2012-05-05
Hi,

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!
0
Comment
Question by:windows_programing
3 Comments
 
LVL 15

Assisted Solution

by:m1tk4
m1tk4 earned 200 total points
ID: 16623576
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;)
0
 
LVL 22

Accepted Solution

by:
earth man2 earned 1000 total points
ID: 16624882
create or replace function random_string( size in integer ) returns text as $$
declare
  s  text := '';
  idx int := 1;
begin

  while (  idx < size ) loop

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

    idx := idx + 1;

  end loop;

  return s;
end;
$$ language plpgsql;


=> select random_string(10);
 random_string
---------------
 kemaprluc
(1 row)
0
 

Author Comment

by:windows_programing
ID: 16633050
Thanks!

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

Featured Post

Granular recovery for Microsoft Exchange

With Veeam Explorer for Microsoft Exchange you can choose the Exchange Servers and restore points you’re interested in, and Veeam Explorer will present the contents of those mailbox stores for browsing, searching and exporting.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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…
By, Vadim Tkachenko. In this article we’ll look at ClickHouse on its one year anniversary.
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.
Integration Management Part 2
Suggested Courses

807 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