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 start with 0 for an empty table and do a 

```
SELECT MAX(ID) FROM table

```

to find the largest id so far. Store it in an AtmoicInteger and convert it using toString

```
AtomicInteger counter = new AtomicInteger(maxSoFar);

String nextId = Integer.toString(counter.incrementAndGet(), 36);

```

or for padding. 36 ^^ 6 = 2176782336L

```
String nextId = Long.toString(2176782336L + counter.incrementAndGet(), 36).substring(1);

```

This will give you uniqueness and no duplicates to worry about. (it's not random either)
For efficient usage, try caching generated code in a `HashSet<String>` in your application:

```
HashSet<String> codes = new HashSet<String>();

```

This way you don't have to make a db call every time to check whether the generated code is unique or not. All you have to do is:

```
codes.contains(newCode);

```

And, yes, you should synchronize your method which updates the cache

```
public synchronize String getCode ()
{
    String newCode = "";
    do {
        newCode = nextString();
    }
    while(codes.contains(newCode));
    codes.put(newCode);
}

```