How can I generate a unique string per record in a table in Postgres?

前端 未结 6 2074
栀梦
栀梦 2020-12-06 04:57

Say I have a table like posts, which has typical columns like id, body, created_at. I\'d like to generate a unique string with the creation of each post, for use in somethin

6条回答
  •  青春惊慌失措
    2020-12-06 05:03

    The easiest way probably to use the sequence to guarantee uniqueness (so after the seq add a fix x digit random number):

    CREATE SEQUENCE test_seq;
    CREATE TABLE test_table (
      id bigint NOT NULL DEFAULT (nextval('test_seq')::text || (LPAD(floor(random()*100000000)::text, 8, '0')))::bigint,
      txt TEXT
    );
    insert into test_table (txt) values ('1');
    insert into test_table (txt) values ('2');
    select id, txt from test_table;
    

    However this will waste a huge amount of records. (Note: the max bigInt is 9223372036854775807 if you use 8 digit random number at the end, you can only have 922337203 records. Thou 8 digit is probably not necessary. Also check the max number for your programming environment!)

    Alternatively you can use varchar for the id and even convert the above number with to_hex() or change to base36 like below (but for base36, try to not expose it to customer, in order to avoid some funny string showing up!):

    PostgreSQL: Is there a function that will convert a base-10 int into a base-36 string?

提交回复
热议问题