Created
April 22, 2020 19:31
-
-
Save hedcler/7a6aa338794fe0b92c6e43536a89cac8 to your computer and use it in GitHub Desktop.
Postgres create random string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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