Skip to content

Instantly share code, notes, and snippets.

@Adron
Created April 26, 2021 08:15
Show Gist options
  • Save Adron/f37ae1f28d2f87153d617183a9c4b43c to your computer and use it in GitHub Desktop.
Save Adron/f37ae1f28d2f87153d617183a9c4b43c to your computer and use it in GitHub Desktop.
Short URL Safe IDs for Postgres
CREATE OR REPLACE FUNCTION gen_unique_short_id() returns text
language plpgsql
as $$
DECLARE
id text;
BEGIN
id := encode(gen_random_bytes(6), 'base64');
id := replace(id, '/', '_');
id := replace(id, '+', '_');
RETURN id;
END;
$$;
alter function gen_unique_short_id() owner to postgres;
@cpursley
Copy link

cpursley commented Jul 8, 2022

You also might be able to get by with:

encode(gen_random_bytes(6), 'hex');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment