in reply to DBI Insert Unique Customer ID

If I understand your question, the advice from Your Mother might be just what you need -- unless you were actually looking for a numeric-string type of value, such as might be used as a "PIN" (personal identifying number) by the person to whom the number is being assigned, in which case as 128-bit (16-character 16-byte, 22-character if base64-encoded) UUID/GUID kind of value might be inappropriate.

Since you specifically mention wanting a "unique but random" number, I assume the other replies about using an "autoincrement" field would be inappropriate as well, since these are not at all random.

A solution I've used in the past (admittedly a kluge with a minor limitation) is to generate a randomized list of numbers first, store that list in a separate table, then select from it sequentially as needed. Include a "status" field along with the randomized numeric value field, and hand out random but unique numbers like this:

my ($pin) = $dbh->selectrow_array( "select pin_value from pins where s +tatus is null limit 1 for update" ); $dbh->do( "update pins set status='used' where pin_value=$pin" );
The "for update" in the select is supposed to keep some other query from fetching the same row until the update has been done.

The limitation, of course, is that you need to make sure the pins table doesn't run out of available rows. It's easy enough to solve with a cron job or something that checks the number of unused rows at regular intervals and adds more whenever it gets too close to zero. In this case, the "add_pins" process just needs to make sure that only adds numbers that haven't been used yet, and that's pretty easy using a hash. For that matter, it's not hard to make sure your initial sequence of random numbers is big enough.

This approach is really nice if you want to put any sort of constraint on the range of possible numeric values being handed out (e.g. they should all be 6-digit, not begin with 0, not contain "666", or whatever).

Replies are listed 'Best First'.
Re^2: DBI Insert Unique Customer ID
by Phatfingers (Initiate) on Apr 09, 2008 at 06:25 UTC
    I've got to concur with using the auto_increment feature of the database to determine the unique ID rather than trying to solve this in Perl from the most recent query. The database app is able to avoid the race condition of two users creating accounts at the same time with both instances coming up with the same number. Listen to Your Mother. Security by obscurity is mostly self-delusion. If user 24000 is able to access someone else's information by typing 24001 in the URL where they see their 24000, then your security problem isn't that 24001 is easy to guess, it's that your guard is down.