Wanted to use a MYSQL query to get random numbers left between 0-999 as a code but tryed that query and also i ended filling the values condition from 0 to 999 and still got always duplicate codes, strange behaviour so i ended up using PHP.
The steps i use now:
Create an array populated with 0 to 999, in the future if i need more codes will use 0 to 9999.
$ary_1 = array(0, 1, 2, ...., 999)
Create other array populated with all codes in the table.
$ary_2 = array(4, 5, 985, 963, 589)
Get a resulting array using array_diff.
$ary_3 = array_diff($ary_1, $ary_2)
Get an array key using array_rand from the resulting array_diff.
$new_code_key = array_rand($ary_3, 1)
Use that key to get the code and create the MYSQL query.
$ary_3[$new_code_key]
Unset that key from the new codes array so i speed up the process and just have to get anoher array_rand key and unset later.
unset($ary_3[$new_code_key])