Generate unique random string to be used as value for a field inside newly created rows in PostgreSQL
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