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
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
);
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.