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;
@filipkis
Copy link

filipkis commented Feb 9, 2014

There is a slight issue with this code. The int4(random() * length(_chars)) will return values from 0 to 36 meaning that occasionally the index will fall out of the scope of 36 characters (more specifically this will happen when it returns 0 as substr counts position in string from 1). In turn, the whole function will return some values that have less then 6 chars.

The following works as expected int4(floor(random() * length(_chars))) + 1. Meaning it will return values in the range of 1 to 36.

@SauloSilva
Copy link

good, thanks guys

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