@tgmarinho
Back to Blog
database

How to create a custom random ID with Postgres

Helper function for creating a custom random ID like a9Kl12

February 15, 20231 min read

Create a function:

CREATE OR REPLACE FUNCTION generate_random_id(length integer)
RETURNS text AS $$
DECLARE
  alphabet text;
  id text := '';
  i integer;
BEGIN
  alphabet := 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  FOR i IN 1..length LOOP
    id := id || substr(alphabet, floor(random() * length(alphabet) + 1)::integer, 1);
  END LOOP;
  RETURN id;
END;
$$ LANGUAGE plpgsql;

Test

SELECT generate_random_id(10); -- returns a random ID with 10 characters

Now you can create a table this way:

CREATE TABLE "public"."product" ("id" text default generate_random_id(6), "name" text NOT NULL, PRIMARY KEY ("id") , UNIQUE ("id"));

Try to insert and select the product table to see the id auto generated.

INSERT INTO product (name) VALUES ('paper');

Done.