This article is half-done without your Comment! *** Please share your thoughts via Comment ***
In this post, I am sharing different scripts for generating a random string in PostgreSQL.
Sometimes, we need to generate a random token and any other random code in the Database System.
The PostgreSQL Provides a random() function to generate a random string with all the possible different numbers, character and symbol.
We can also use random() function with cryptography or encryption function to generate a fixed length binary string.
Generate a random string using MD5():
1 2 3 4 5 6 7 8 |
SELECT MD5(random()::text); /* Result: md5 text ------------------------------------- 5815789cc68c2c4a8a46e31c72f0a327 */ |
Generate a Capital Latter random string, size of 15:
1 2 3 4 5 6 7 8 9 |
SELECT array_to_string(ARRAY(SELECT chr((65 + round(random() * 25)) :: integer) FROM generate_series(1,15)), ''); /* Result: array_to_string text ------------------- ZPGVXSNNTWFBMDY */ |
Generate a Small Latter random string, size of 15:
1 2 3 4 5 6 7 8 9 |
SELECT array_to_string(ARRAY(SELECT chr((97 + round(random() * 25)) :: integer) FROM generate_series(1,15)), ''); /* Result: array_to_string text ----------------- ohmqjtxxqbtqinq */ |
Generate a Numerical random string, size of 15:
1 2 3 4 5 6 7 8 9 |
SELECT array_to_string(ARRAY(SELECT chr((48 + round(random() * 9)) :: integer) FROM generate_series(1,15)), ''); /* Result: array_to_string text ----------------- 132443402808481 */ |
Generate a random string with all combinations, size of 15:
1 2 3 4 5 6 7 8 9 |
SELECT array_to_string(ARRAY(SELECT chr((48 + round(random() * 59)) :: integer) FROM generate_series(1,15)), ''); /* Result: array_to_string text ----------------- `E07 */ |