Skip to content

Instantly share code, notes, and snippets.

@robcowie
Created December 30, 2011 13:22
Show Gist options
  • Save robcowie/1539835 to your computer and use it in GitHub Desktop.
Save robcowie/1539835 to your computer and use it in GitHub Desktop.
Postgresql function to generate unique alpha-numeric codes
-- Actually, if UNIQUE is defined on the col, there is no need to store previous codes
-- It will fail to insert due to uniqueness contraint when all possible codes are exhausted
-- Use as a column default...
-- CREATE TABLE foo (id CHAR(6) DEFAULT AlphaNumericSerial() UNIQUE);
CREATE OR REPLACE FUNCTION AlphaNumericSerial()
RETURNS char(6) AS $$
DECLARE _serial char(6); _i int; _chars char(36) = 'abcdefghijklmnopqrstuvwxyz0123456789';
BEGIN
_serial = '';
FOR _i in 1 .. 6 LOOP
_serial = _serial || substr(_chars, int4(random() * length(_chars)), 1);
END LOOP;
RETURN lower(_serial);
END;
$$ LANGUAGE plpgsql VOLATILE;
@SauloSilva
Copy link

good, thanks guys

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment