Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I insert random characters into a sql database column?

Tags:

sql

sql-server

I want to populate a column of my database table with 253 lines of 'M' and 'F' randomly placed in the column, is this possible?

Example of what it may look like:

Gender:
M
M
F
M
F
F
M
F
M
like image 816
GeorgeB Avatar asked Jul 05 '17 12:07

GeorgeB


People also ask

How do you add random values in SQL?

To create a random integer number between two values (range), you can use the following formula: SELECT FLOOR(RAND()*(b-a+1))+a; Where a is the smallest number and b is the largest number that you want to generate a random number for.

How do I randomly sample in SQL?

To get a single row randomly, we can use the LIMIT Clause and set to only one row. ORDER BY clause in the query is used to order the row(s) randomly. It is exactly the same as MYSQL. Just replace RAND( ) with RANDOM( ).

How do I generate a random key in SQL?

SQL Server RAND() Function The RAND() function returns a random number between 0 (inclusive) and 1 (exclusive).


1 Answers

For MS SQL you can use NEWID and CHECKSUM functions like:

  UPDATE Users 
  SET Gender = (CASE WHEN ABS(CHECKSUM(NEWID()) % 2) = 1 THEN 'M' ELSE 'F' END)
  • NEWID() will generate random GUID

  • CHECKSUM() will generate hash of that GUID

  • ABS() to make it either 1 or 0


WARNING! While some people suggesting to use RAND function - please do not use it for this particular case. The query like this:

UPDATE Users SET Gender = CASE WHEN (RAND() > 0.5) THEN 'M' ELSE 'F' END

.. will result that you have all values either M or either F.

Potentially you can seed RAND function with some value like Id, but distribution of values will be not very good: like first 30-40% all M, then 30-40% all F, then M again.

like image 61
Pavel Morshenyuk Avatar answered Nov 03 '22 10:11

Pavel Morshenyuk