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.

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more