Managing the Incrementing Key Pattern

Epwna, you should also consider that an incrementing key has to be stored in a common location and updated with every insert (i.e. a singleton). Back when relational was all the rage, it wasn’t a big deal because databases lived on one machine. Now we’re distributing across clusters of servers so introducing a singleton resource has become somewhat of an anti-pattern. The few bytes you spend on statistically unique keys (GUIDs) over auto-increment is pretty much irrelevant too.

In .NET, I use the following to generate URI compatible compacted GUIDs:

// GUIDs contain a maximum of 22 useful characters when Base64 encoded.
string identifier = Convert.ToBase64String(Guid.NewGuid().ToByteArray());

// Trim off any trailing ‘=’ signs that remain after encoding.
identifier = identifier.Substring(0, 22);

// Replace any URI-incompatible Base64 characters
identifier = identifier.Replace("/", “_”);
identifier = identifier.Replace("+", “-”);

return identifier;

These are pretty tight and don’t use unprintable characters. They do mix upper- and lower-case, so they’re not suited for manual entry or reading over a phone though. In those scenarios, I use a pseudonym that sometimes returns multiple hits or require additional selection criteria, like customer ID.