Prepare for the PgBouncer and IPv4 deprecations on 26th January 2024

Home

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

  1. Go to the Database page in the Dashboard.
  2. Click on Extensions in the sidebar.
  3. Search for "pg_hashids" and enable the extension.

Usage

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 pg_hashid's id_encode function.


_21
create table orders (
_21
id serial primary key,
_21
description text,
_21
price_cents bigint
_21
);
_21
_21
insert into orders (description, price_cents)
_21
values ('a book', 9095);
_21
_21
select
_21
id,
_21
id_encode(id) as short_id,
_21
description,
_21
price_cents
_21
from
_21
orders;
_21
_21
id | short_id | description | price_cents
_21
----+----------+-------------+-------------
_21
1 | jR | a book | 9095
_21
(1 row)

To reverse the short_id back into an id, there is an equivalent function named id_decode.

Resources