PostgreSQL

PostgreSQL 乱数作成

お手軽に英数字を使ったランダム文字列作成

MD5ハッシュは16進表現となるので、出力されるのは0-9、a-fの範囲内でのランダム文字です

select substr(md5(random()::text || now()::text),1,32) as random_string
;

random() ランダムな浮動小数点数を生成(明示的なキャストは不要だけど今回はつけてます)
now()::text システム時間を文字列化
md5() 上記連結文字列をMD5でハッシュ
substr() で先頭から32文字を抽出

myposdb=# select substr(md5(random()::text || now()::text),1,32) as random_string
myposdb-# ;
          random_string
----------------------------------
 2a6f0f7b42b3e39569908eca9227c1fd
(1 行)


myposdb=#
お手軽に英数字を使ったランダム文字列作成
select array_to_string(array(select chr((48 + round(random() * 74))::integer) 
from generate_series(1,32)), '') as random_string;
myposdb=# select array_to_string(array(select chr((48 + round(random() * 74))::integer) 
from generate_series(1,32)), '') as random_string;
          random_string
----------------------------------
 thnRk]ux=x8Fmd_BluW4dvWUakyM]=Q<
(1 行)


myposdb=#
少し解説します
以下SQLでは、asciiコード表の48~122番の文字をランダムに出力しています。
select chr((48 + round(random() * 74))::integer);

また、from generate_series(1,32)とする事で、32件の結果セットを返却しています。

array_to_string()の第2パラメータを''としている事で、区切り文字無しで文字列化しています。
少しこだわって対象文字を外したり追加したりしてみました
select string_agg(chr(ascii_value), '')
from (
    select ascii_value
    from (
        select generate_series(48, 122) as ascii_value
        union all
        select 33 as ascii_value  -- ! を候補に追加
        union all
        select 35 as ascii_value  -- # を候補に追加
        union all
        select 37 as ascii_value  -- % を候補に追加
    ) as all_values
	-- ; , : , = , ? , @ を候補から除く
    where ascii_value not in (58, 59, 61, 63, 64)
    order by random()
    limit 20
) as random_chars;
myposdb=# select string_agg(chr(ascii_value), '')
myposdb-# from (
myposdb(#     select ascii_value
myposdb(#     from (
myposdb(#         select generate_series(48, 122) as ascii_value
myposdb(#         union all
myposdb(#         select 33 as ascii_value  -- ! を候補に追加
myposdb(#         union all
myposdb(#         select 35 as ascii_value  -- # を候補に追加
myposdb(#         union all
myposdb(#         select 37 as ascii_value  -- % を候補に追加
myposdb(#     ) as all_values
myposdb(#   -- ; , : , = , ? , @ を候補から除く
myposdb(#     where ascii_value not in (58, 59, 61, 63, 64)
myposdb(#     order by random()
myposdb(#     limit 20
myposdb(# ) as random_chars;
      string_agg
----------------------
 ]37pU0wSfoeMRKX%d2qb
(1 行)


myposdb=#
スポンサーリンク
タイトルとURLをコピーしました