Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random names in sql

I have 5 random names each for male and female. I need to insert random names based on the gender. But how can we insert names in random from a set of 5 names in SQL. Is it possible?

like image 986
user2471553 Avatar asked Dec 01 '22 19:12

user2471553


2 Answers

select name from table order by newid()
like image 158
Md. Parvez Alam Avatar answered Jan 02 '23 21:01

Md. Parvez Alam


Create a table with the names, and an integer ID. Then use RAND() with % 5 to get down to a value between 0 and 4 inclusively. Add 1 if you want a male, and 6 if you want a female. Like so:

Create table RandomNames
(id int,
 name varchar(100),
 gender char(1)
)

insert into RandomNames
(id, name,gender)
select 1,'Bill','M'
union
select 2,'John','M'
union
select 3,'Steve','M'
union
select 4,'Mike','M'
union
select 5,'Phil','M'
union
select 6,'Sarah','F'
union
select 7,'Ann','F'
union
select 8,'Marie','F'
union
select 9,'Liz','F'
union
select 10,'Stephanie','F'

declare @wantedGender char(1)

select @wantedGender = 'M'

select name 
from RandomNames
where id =  (CAST(RAND()*100 as int) % 5) + case when @wantedGender = 'M' then 1 else 6 end 
like image 44
Bill Gregg Avatar answered Jan 02 '23 22:01

Bill Gregg