I needed to create a unique field that is not the unique ID of the row on the table, i.e. a human-readable referral code my users can pass on to others, in the format user name+5 digits.
To first search to see if the code is used and if not, add it could, yes the chance being slim, lead to duplicates. So I came up with this process:
- Generate code
- Store the code in the DB.
- Check if the code is used >1 time. If so, goto 1.
- Mark this Users code as unique and never do this loop again for this user.
Could this be a good best practice or is there a better way?