Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL insert unique technique

Tags:

php

mysql

unique

I have a php application that inserts a data into MySQL, which contains a randomly-generated unique value. The string will have about 1 billion possibilities, with probably no more than 1 or 2 million entries at any one time. Essentially, most combinations will not exist in the database.

I'm trying to find the least expensive approach to ensuring a unique value on insert. Specifically, my two options are:

  1. Have a function that generates this unique ID. On each generation, test if the value exists in the database, if yes then re-generate, if no, return value.
  2. Generate random string and attempt insert. If insert fails, test error is 1062 (MySQL duplicate entry X for key Y), re-generate key and insert with new value.

Is it a bad idea to rely upon the MySQL error for re-trying the insert? As I see it, the value will probably be unique, and it seems the initial (using technique 1) would be unnecessary.

EDIT #1

I should have also mentioned, the value must be a 6 character length string, composed of either uppercase letters and/or numbers. They can't be incremental either - they should be random.

EDIT #2

As a side note, I'm trying to create a redemption code for a gift certificate that is difficult to guess. Using numbers and letters creates 36 possibilities for each character, instead of 10 for just numbers or 26 for just letters.

Here's a stripped-down version of the solution I created. The first value entered in the table is the primary key, which is auto incremented. affected_rows() will equal 1 if the insert is successful:

 $code = $build_code();
 while ((INSERT INTO certificates VALUES ('', $code) ON DUPLICATE KEY UPDATE pk = pk) && affected_rows() == 0)
      $code = $build_code();
like image 273
Eric Di Bari Avatar asked Nov 13 '22 10:11

Eric Di Bari


1 Answers

Is it a bad idea to rely upon the MySQL error for re-trying the insert?

Nope. Go ahead an use it if you want. In fact many people think if you check and if it doesn't exist then it's safe to insert. But unless you lock the table it's always possible that another process might slip in and grab the id.

So go ahead generate a random id if it suits your purpose. Just make sure you test your code so it does properly handle dups. Might also be useful to log dups just to ensure your assumptions about how unlikey dups are to occur are correct.

like image 97
Cerad Avatar answered Nov 16 '22 04:11

Cerad