Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to produce random hex color in sql?

Tags:

It's pretty hard topic for me because SQL is not my best skill ;)

I must insert random hex colors into database row. How can I do it? Is it possible to create function that will draw numbers?

like image 701
Mr Jedi Avatar asked Mar 09 '14 13:03

Mr Jedi


People also ask

What is random color hex?

The colors are generated with true randomness originating from atmospheric noise. Hexadecimal color codes are used to represent colors numerically as three values in the [0,255] range: red, green and blue. The greater each value, the higher the intensity of the corresponding component.

How are colors stored in a database?

If you just need to store the color, then hex notation should be fine. If you need to perform queries against specific color channels, then you'd want smallint fields for each color channel (be it RGB, ARGB, CYMK, etc). So, for simple storage, keep it simple.


2 Answers

SET [Color] =  '#' +  CONVERT(VARCHAR(max), CRYPT_GEN_RANDOM(3), 2) 
like image 110
Ahmed Eid Yamany Avatar answered Sep 20 '22 15:09

Ahmed Eid Yamany


Here is the logic explained below wrapped in a function for MySQL. It's very easy to use.

mysql> select random_color(); +----------------+ | random_color() | +----------------+ | #8F50B4        | +----------------+ 1 row in set (0.00 sec) 

It can be called over and over again and each time it will have a different color.

CREATE FUNCTION `random_color`() RETURNS char(7) CHARSET latin1 DETERMINISTIC BEGIN  DECLARE str CHAR(7);  SET str = concat('#',SUBSTRING((lpad(hex(round(rand() * 10000000)),6,0)),-6));  RETURN str; END; 

This will give you six digit hex number codes in MySQL

SELECT concat('#',SUBSTRING((lpad(hex(round(rand() * 10000000)),6,0)),-6)) 

Here's a great one that will give you incremental colors

SELECT *,         concat('#',SUBSTRING((lpad(hex(@curRow := @curRow + 10),6,0)),-6)) AS color  FROM table         INNER JOIN (SELECT @curRow := 5426175) color_start_point 
like image 35
jbrahy Avatar answered Sep 19 '22 15:09

jbrahy