Tuesday 2 June 2015

Mysql: How to generate random char

All characters have their own codes, for example ASCII codes of uppercase latin characters have codes from 65 to 90, respectively 'A' = 65 and 'Z' = 90.
Function CHAR returns the character for passed integer value -
SELECT CHAR(65) col1, CHAR(66) col2, CHAR(67) col3, CHAR(90) col4;
+------+------+------+------+
| col1 | col2 | col3 | col4 |
+------+------+------+------+
| A    | B    | C    | Z    |
+------+------+------+------+
Using the method of generating random numbers described in the MySQL documentation, you can get the generator of random characters for codes from 65 to 90 -
SELECT CHAR(FLOOR(65 + (RAND() * 25))) AS any_char;
+----------+
| any_char |
+----------+
| E        |
+----------+
SELECT CHAR(FLOOR(65 + (RAND() * 25))) AS any_char;
+----------+
| any_char |
+----------+
| K        |
+----------+

0 comments:

Post a Comment