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
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.
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( ).
SQL Server RAND() Function The RAND() function returns a random number between 0 (inclusive) and 1 (exclusive).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With