Can I create column in DB table (PostgreSQL) which have default value random string, and how ?
If is not possible, please let me know that.
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It only takes a minute to sign up.Sign up to join this community
CREATE OR REPLACE FUNCTION f_random_text( length integer ) RETURNS text AS $body$ WITH chars AS ( SELECT unnest(string_to_array('A B C D E F G H I J K L M N O P Q R S T U V W X Y Z 0 1 2 3 4 5 6 7 8 9', ' ')) AS _char ), charlist AS ( SELECT _char FROM chars ORDER BY random() LIMIT $1 ) SELECT string_agg(_char, '') FROM charlist ; $body$ LANGUAGE sql; DROP TABLE IF EXISTS tmp_test; CREATE TEMPORARY TABLE tmp_test ( id serial, data text default f_random_text(12) ); INSERT INTO tmp_test VALUES (DEFAULT, DEFAULT), (DEFAULT, DEFAULT) ; SELECT * FROM tmp_test; id | data ----+-------------- 1 | RYMUJH4E0NIQ 2 | 7U4029BOKAEJ (2 rows)
Apparently you can do this. (Of course, you can add other characters as well, or use other random string generator as well - like this, for example.)