How to generate a GUID/UUID?

  • What is the best way to generate a GUID/UUID from Apex code (such as a trigger)? Preferably in the following format:




    @techtrekker: That looks very promising. Is it standalone and tested. I.e. do you have experience with it? Btw, you should post that as an answer. I'll give it a try and most likely will mark it as an answer.

    I haven't personally tried it, which is why I posted it as a comment.

    Glad it helped, and a good answer now awaits anyone who might need this in the future !

  • Paul Sasik

    Paul Sasik Correct answer

    9 years ago

    After working with the code in techtrekker's link (in OP comments) and other resources I cobbled together a standalone, working class for generating GUIDs in Apex code:

    Sample usage:

       if (acct.AccountUuid__c == null)
            acct.AccountUuid__c = GuidUtil.NewGuid();

    Apex class:

    global class GuidUtil {
        private static String kHexChars = '0123456789abcdef';
        global static String NewGuid() {
            String returnValue = '';
            Integer nextByte = 0;
            for (Integer i=0; i<16; i++) {
                if (i==4 || i==6 || i==8 || i==10) 
                    returnValue += '-';
                nextByte = (Math.round(Math.random() * 255)-128) & 255;
                if (i==6) {
                    nextByte = nextByte & 15;
                    nextByte = nextByte | (4 << 4);
                if (i==8) {
                    nextByte = nextByte & 63;
                    nextByte = nextByte | 128;
                returnValue += getCharAtIndex(kHexChars, nextByte >> 4);
                returnValue += getCharAtIndex(kHexChars, nextByte & 15);
            return returnValue;
        global static String getCharAtIndex(String str, Integer index) {
            if (str == null) return null;
            if (str.length() <= 0) return str;    
            if (index == str.length()) return null;    
            return str.substring(index, index+1);

    The reference to `StringUtils` should be removed if this is supposed to be a standalone class. Good post nonetheless!

    I have seen this procedure before. While it's very good, I have seen test methods once in a while give duplicates using this. The reason is the math.random which as we all know is not random at all. So the possibility exists of duplicates even with this. I think this needs to be increased to 1024 to lessen the possibility, but mostly - SALESFORCE; CREATE A STRING.NEWGUID() FUNCTION! Every language has it!

    I know this is old, but: The code by Paul Sasik is good to generate some random ID, but it has no guarantee that it is "unique", as in GUID, or UUID. Regards, Allan

License under CC-BY-SA with attribution

Content dated before 7/24/2021 11:53 AM

Tags used