How to create a custom random ID with Postgres
Thiago Marinho
Posted on February 15, 2023
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.
💖 💪 🙅 🚩
Thiago Marinho
Posted on February 15, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.