Search code examples
mysqlrandomvarchar

Generate a random value that doesn't exist in the same column


I already googled it, but I just found similar answers.
I'm not a back-end developer, so I don't know a lot of SQL. I need to generate and insert a 6 digit random value that involves numbers and characters (varchar, I think) that doesn't exist in the same column.

I tried this FLOOR(RAND() * 401) + 100 that I found somewhere, but it just generate numbers and... nothing more.

I'm lost.

Please, masters of databases, light my way with your random numbers ;-;


Solution

  • SELECT LPAD(CONV(RAND() * POW(36, 6), 10, 36), 6, 0)
    

    This will create a 6 character "random" alphanumeric value.

    But:

    • You will need to check if the value already exists in your table.
    • The distribution is not equal, because rand() retuns a FLOAT which only has a precision of 23 bit, while POW(36, 6) needs something like 32 bit.

    Update:

    However - because you will need to check, if the value already exists, you better create the number in PHP.

    $success = false;
    while (!$success) {
        $rndInt = rand(0, pow(36, 6) - 1);
        $rndStr = base_convert ($rndInt, 10, 36);
        $rndStr = str_pad($rndStr , 6, "0", STR_PAD_LEFT);
    
        $query = "SELECT 1 FROM your_table WHERE your_column = {$rndStr} LIMIT 1";
        $db->query($query);
        if (!$db->fetchColumn()) { // value does not exist yet
            // insert new random value
            $query = "INSERT INTO your_table (your_column) VALUES ({$rndStr})";
            $db->query($query);
            $success = true; // will terminate the loop
        } else { // value already exists
            // do nothing - try again in the next loop
        }
    }
    

    You will need to ajust the code to what ever you use for MySQL communication.