Created
April 30, 2022 16:05
-
-
Save chris-kobrzak/b894b69f196993ef427ef5d435a85810 to your computer and use it in GitHub Desktop.
PostgreSQL helper for generating random strings of variable length
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 gen_random_string(_min_length INT = 3) | |
RETURNS VARCHAR | |
LANGUAGE SQL | |
AS ' | |
SELECT substring( | |
md5(random()::TEXT), | |
0, | |
_min_length + floor(random() * 10 + 1)::INT | |
) | |
'; | |
COMMENT ON FUNCTION gen_random_string IS 'Generates from 3 to 3 + 10 random characters'; | |
-- Test it | |
CREATE TABLE random_strings ( | |
id INTEGER GENERATED BY DEFAULT AS IDENTITY, | |
string VARCHAR, | |
PRIMARY KEY (id) | |
); | |
DO | |
$do$ | |
BEGIN | |
FOR index IN 1..10 LOOP | |
INSERT INTO random_strings (string) | |
SELECT gen_random_string(); | |
END LOOP; | |
END | |
$do$; | |
/* Results: | |
id string | |
------------ | |
1 b87f | |
2 6c38fc9 | |
3 c2fba8 | |
4 29165352a1 | |
5 6af1c30 | |
6 d5409 | |
7 b70b297 | |
8 f2fd | |
9 65e2 | |
10 94f1ac34 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment