Skip to content

Instantly share code, notes, and snippets.

@robcowie
Created April 30, 2020 10:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robcowie/e6438369c205c75103ba5e94e09a2f70 to your computer and use it in GitHub Desktop.
Save robcowie/e6438369c205c75103ba5e94e09a2f70 to your computer and use it in GitHub Desktop.
Generate random strings in Postgresql
-- Fixed-length ascii strings
CREATE OR REPLACE FUNCTION pg_temp.random_string(int) RETURNS text
AS $$ SELECT
array_to_string(ARRAY(SELECT chr(ascii('B') + round(random() * 25)::integer)
FROM
generate_series(1, $1)), '') $$
LANGUAGE sql;
select pg_temp.random_string(8);
INSERT INTO tbl (a, b)
SELECT pg_temp.random_string(8), initcap(array_to_string(ARRAY(SELECT pg_temp.random_string(4) FROM generate_series(1, 3)), ' '))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment