How to generate a random, unique, alphanumeric ID of length N in Postgres 9.6+?

后端 未结 6 615
走了就别回头了
走了就别回头了 2020-12-25 14:59

I\'ve seen a bunch of different solutions on StackOverflow that span many years and many Postgres versions, but with some of the newer features like gen_random_bytes I want

6条回答
  •  余生分开走
    2020-12-25 15:40

    I'm looking for something that gives me "shortcodes" (similar to what Youtube uses for video IDs) that are as short as possible while still containing only alphanumeric characters.

    This is a fundamentally different question from what you first asked. What you want here then is to put a serial type on the table, and to use hashids.org code for PostgreSQL.

    • This returns 1:1 with the unique number (serial)
    • Never repeats or has a chance of collision.
    • Also base62 [a-zA-Z0-9]

    Code looks like this,

    SELECT id, hash_encode(foo.id)
    FROM foo; -- Result: jNl for 1001
    
    SELECT hash_decode('jNl') -- returns 1001
    

    This module also supports salts.

提交回复
热议问题