DEV Community

Thiago Marinho
Thiago Marinho

Posted on

6

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.

Neon image

Serverless Postgres in 300ms (❗️)

10 free databases with autoscaling, scale-to-zero, and read replicas. Start building without infrastructure headaches. No credit card needed.

Try for Free →

Top comments (0)

Image of Stellar post

Check out Episode 1: How a Hackathon Project Became a Web3 Startup 🚀

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more