1

I Want Auto Generate Alphanumeric(AANNNN) id's in postgresql. for eg=AA0001,AA9999,AB0001. And the Order of value increment from right to left.

1 Answer 1

2

Create a SERIAL column (auto-incrementing), then create a computed column with the following definition:

CREATE TABLE t (
  ID SERIAL,
  CharID varchar(10) GENERATED ALWAYS AS (
      CHR(65 + ID / 260000) ||
      CHR(65 + MOD(ID / 10000, 26)) ||
      lpad(MOD(id, 260000)::text, 4, '0')
    ) STORED
);

db<>fiddle

It's simple arithmetic: uppercase letters begin at character 66, and there are 26 of them. So the first two lines create those two, using integer division and modular division. Then use modular division again to get the final 4 digits.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.