Initial goal:
I would like to generate random and unique codes (6 digits) in a table. I use a SQL query like this one to do that:
SELECT SUBSTRING(CRC32(RAND()), 1, 6) as myCode
FROM `codes`
HAVING myCode NOT IN (SELECT code FROM `codes`)
I asked me about how it will react when there will be no more available codes so I do the following test
Test context:
MySQL version: 5.5.20
MySQL Table:
CREATE TABLE `codes` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`code` VARCHAR( 10 ) NOT NULL ,
UNIQUE (
`code`
)
) ENGINE = InnoDB;
Initial data:
INSERT INTO `codes` (`id`, `code`)
VALUES (NULL, '1'), (NULL, '2'), (NULL, '3'), (NULL, '4'), (NULL, '5'), (NULL, '6'), (NULL, '7'), (NULL, '8');
SQL Query:
SELECT SUBSTRING(CRC32(RAND()), 1, 1) as myCode
FROM `codes`
HAVING myCode NOT IN (SELECT code FROM `codes`)
By execute this query, I expect that it will always return 9 because it is the only code of one digit which does not exists.
But the result is:
- Sometime it return any rows
- Sometime it return rows with values that already exists
I don't understand this behavior so if someone can help :)
So the big question is:
How MySQL can return rows with values that already exists?
Thanks
I would fill a
sequencetable
table with all the possible values, in sequence.Then the random query just randomly selects records from the
sequencetable
, and each time it picks a record it deletes it. This way you will surely get all the numbers, without wasting time in finding a "hole" number (not already picked up).Fill the sequence (no need for the AUTOINCREMENT actually).
Select a random record from the sequence (do this in a loop until records are available):
(I understand that this way of generating is a kind of proof of concept)
The very strange thing is how this request could return an already existing value????