pg_hashids: Short UIDs
pg_hashids provides a secure way to generate short, unique, non-sequential ids from numbers. The hashes are intended to be small, easy-to-remember identifiers that can be used to obfuscate data (optionally) with a password, alphabet, and salt. For example, you may wish to hide data like user IDs, order numbers, or tracking codes in favor of
pg_hashid's unique identifers.
Enable the Extension#
- Go to the Database page in the Dashboard.
- Click on Extensions in the sidebar.
- Search for "pg_hashids" and enable the extension.
Suppose we have a table that stores order information, and we want to give customers a unique identifer without exposing the sequential
id column. To do this, we can use
_21create table orders (_21id serial primary key,_21description text,_21price_cents bigint_21);_21_21insert into orders (description, price_cents)_21values ('a book', 9095);_21_21select_21id,_21id_encode(id) as short_id,_21description,_21price_cents_21from_21orders;_21_21id | short_id | description | price_cents_21----+----------+-------------+-------------_211 | jR | a book | 9095_21(1 row)
To reverse the
short_id back into an
id, there is an equivalent function named
- Official pg_hashids documention