Generate unique random string to be used as value for a field inside newly created rows in PostgreSQL I have this statement which generate a random string:

SELECT string_agg (substr('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', ceil (random() * 62)::integer, 1), '')
FROM generate_series(1, 20);


My question, how to implement this inside a function which would assign the value of the above statement automatically to a field named url_prefix when new records are created (on INSERT's) ?
You can create a function and use it as the default for the column:




create function f() returns text language sql as $$
  SELECT string_agg (substr('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', ceil (random() * 62)::integer, 1), '')
  FROM generate_series(1, 20)
$$;

create table foo(id serial primary key, url_prefix text not null default f());

insert into foo default values;






select * from foo;



id | url_prefix          
-: | :-------------------
 1 | iByDaJ2h4JHi3dI3uBoy



db&lt;>fiddle here