title: generate 16M unique random numbers
body: <p>I'm trying to generate 16 000 000 unique random numbers (10-digits: range 1 000 000 000 - 9 999 999 999) and insert them into an empty table (or fill this table up if not empty).</p>
  
  <p>The table:</p>
  
  <pre><code>CREATE TABLE `codes` (
  `code_id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `code` bigint(20) UNSIGNED NOT NULL,
  `is_used` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`code_id`),
  UNIQUE KEY `code` (`code`)
  ) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
  </code></pre>
  
  <p>...and the function:</p>
  
  <pre><code>DELIMITER $$
  
  CREATE DEFINER=`root`@`localhost` FUNCTION `codes`(`minRange` BIGINT UNSIGNED, `maxRange` BIGINT UNSIGNED, `_amount` BIGINT UNSIGNED) RETURNS tinyint(1)
  MODIFIES SQL DATA
  BEGIN
  DECLARE pick BIGINT;
  
  
  while (SELECT count(*) FROM codes) &lt; _amount do
  begin
  SET pick = minRange + FLOOR(RAND() * (maxRange - minRange + 1));
  INSERT IGNORE INTO codes (code) VALUES (pick);
  
  end;
  end while;
  
  RETURN 1;
  END$$
  
  DELIMITER ;
  
  -- call: SELECT codes(1000000000,9999999999,16000000);
  </code></pre>
  
  <p>The function is extremaly slow: generating 20k rows takes 2.5 min., so 16M - about 33 hours...
  Is there any way to optimise it?</p>