Question: My webapplication has a table in the database with an `id` column which will always be unique for each row. In addition to this I want to have another column called `code` that will have a 6 digit unique Alphanumeric code with numbers 0-9 and alphabets A-Z. Alphabets and number can be duplicate in a code. i.e. `FFQ77J`. I understand the uniqueness of this 6 digit alphanumeric code reduces over time as more rows are added but for now I am ok with this. 

**Requirement (update)**
 - The code should be at least of length 6 
 - Each code should be Alphanumeric 

So I want to generate this Alphanumeric code. 

**Question**

What is a good way to do this? 

* Should I generate the code and after the generation, run a query to the database and check if it already exists, and if so then generate a new one? To ensure the uniqueness, does this piece of code need to be synchronized so that only one thread runs it?
* Is there something built-in to the database that will let me do this?

For the generation I will be using something like this which I saw in [this answer](https://stackoverflow.com/a/41156/44286)

```
char[] symbols = new char[36];
char[] buf;
    for (int idx = 0; idx < 10; ++idx)
        symbols[idx] = (char) ('0' + idx);
    for (int idx = 10; idx < 36; ++idx)
        symbols[idx] = (char) ('A' + idx - 10);
public String nextString()
{
    for (int idx = 0; idx < buf.length; ++idx)
        buf[idx] = symbols[random.nextInt(symbols.length)];
    return new String(buf);
}

```

Answer: 
I would simply do this:

```
String s = Integer.toString(i, 36).toUpperCase();

```

Choosing base-36 will use characters 0-9a-z for the digits. To get a string that uses uppercase letters (as per your question) you would need to fold the result to upper case.

If you use an auto increment column for your id, set the next value to at least `60,466,176`, which when rendered to base 36 is `100000` - always giving you a 6 digit number.
Simply, you can use `Integer.toString(int i, int radix)`. Since you have base 36(26 letters+10 digits) you set the radix to 36 and `i` to your integer. For example, to use `16501`, do:

```
 String identifier=Integer.toString(16501, 36);

```

You can uppercase it with `.toUpperCase()`

Now onto your other questions, yes, you should query the database first to ensure it doesn't exist. If depending on the database, it may need to be synchronized, or it may not be as it'll use its own locking system. In any case, you'd need to tell us *which* database.

On the question of whether there's a builtin, we'd need to know the DB type as well.