Skip to content

Instantly share code, notes, and snippets.

@hedcler
Created April 22, 2020 19:31
Show Gist options
  • Save hedcler/7a6aa338794fe0b92c6e43536a89cac8 to your computer and use it in GitHub Desktop.
Save hedcler/7a6aa338794fe0b92c6e43536a89cac8 to your computer and use it in GitHub Desktop.
Postgres create random string
CREATE OR REPLACE FUNCTION get_random_string(
IN string_length INTEGER,
IN possible_chars TEXT DEFAULT '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
) RETURNS text
LANGUAGE plpgsql
AS $$
DECLARE
output TEXT = '';
i INT4;
pos INT4;
BEGIN
FOR i IN 1..string_length LOOP
pos := 1 + CAST( random() * ( LENGTH(possible_chars) - 1) AS INT4 );
output := output || substr(possible_chars, pos, 1);
END LOOP;
RETURN output;
END;
$$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment