views:

52

answers:

3

I'd like to make a random string for use in session verification using postgresql. I know I can get a random number with "Select random()", so I tried "select md5(random())", but that doesn't work. How can I do this?

A: 

Why is this tagged postgresql, but you your question states mysql?

I would use pl/perl and use this module http://search.cpan.org/~steve/String-Random-0.20/Random.pm.

Why do any extra work?

StarShip3000
Actually you will need to use PL/PerlU (untrusted) in order to require the random module. Check the docs out on what this means http://www.postgresql.org/docs/9.0/interactive/plperl-trusted.html
StarShip3000
A: 

There's NO builtin MD5 function. You need to install pgcrypto contrib module and then use:

SELECT digest(<your_data>,'md5');

Of course that's all if you really mean to use Postgres as you tag and title indicate and not MySQL as your question indicates.

Milen A. Radev
+2  A: 

I'd suggest this simple solution:

this is a quite simple function that returns random string of the given length:

create or replace function random_string(length integer) returns text as 
$$
declare
  chars text[] := '{0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z}';
  result text := '';
  i integer := 0;
begin
  if length < 0 then
    raise exception 'Given length cannot be less than 0';
  end if;
  for i in 1..length loop
    result := result || chars[1+random()*(array_length(chars, 1)-1)];
  end loop;
  return result;
end;
$$ language plpgsql;

and the usage:

select random_string(15);

example output:

select random_string(15) from generate_series(1,15);

  random_string  
-----------------
 5emZKMYUB9C2vT6
 3i4JfnKraWduR0J
 R5xEfIZEllNynJR
 tMAxfql0iMWMIxM
 aPSYd7pDLcyibl2
 3fPDd54P5llb84Z
 VeywDb53oQfn9GZ
 BJGaXtfaIkN4NV8
 w1mvxzX33NTiBby
 knI1Opt4QDonHCJ
 P9KC5IBcLE0owBQ
 vvEEwc4qfV4VJLg
 ckpwwuG8YbMYQJi
 rFf6TchXTO3XsLs
 axdQvaLBitm6SDP
(15 rows)
Simon