DEV Community

Thiago Marinho
Thiago Marinho

Posted on

How to create a custom random ID with Postgres

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;
Enter fullscreen mode Exit fullscreen mode

Test

SELECT generate_random_id(10); -- returns a random ID with 10 characters
Enter fullscreen mode Exit fullscreen mode

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"));
Enter fullscreen mode Exit fullscreen mode

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

INSERT INTO product (name) VALUES ('paper');
Enter fullscreen mode Exit fullscreen mode

Done.

Top comments (0)