Selecting a Random Set of Rows from a Table

Moderator: NorbertKrupa

id10t
GURU
GURU
Posts: 732
Joined: Mon Apr 16, 2012 2:44 pm

Re: Selecting a Random Set of Rows from a Table

Post by id10t » Wed Jun 13, 2012 10:32 pm

For exact 3 colours or N colours use in query of @doug_harmon:

Code: Select all

truncate table ColorsRand; 
insert into ColorsRand select subquery.colour from (select random() + randomint(100), colour from Colors order by 1) as subquery limit 3; 
select * from Colors left outer join ColorsRand on Colors.colour = ColorsRand.colour;

Code: Select all

TRUNCATE TABLE
 OUTPUT 
--------
      3
(1 row)

 colour  | colour  
---------+---------
 #DCDCDC | #DCDCDC
 #FFCCBB | 
 Black   | 
 Blue    | 
 Green   | 
 Magenta | Magenta
 Orange  | 
 White   | 
 Yellow  | Yellow
(9 rows)

User avatar
JimKnicely
Site Admin
Site Admin
Posts: 1825
Joined: Sat Jan 21, 2012 4:58 am
Contact:

Re: Selecting a Random Set of Rows from a Table

Post by JimKnicely » Thu Jun 14, 2012 3:25 pm

insert into ColorsRand select subquery.colour from (select random() + randomint(100), colour from Colors order by 1) as subquery limit 3;
If you need to do this on a larger scale, you can change the subquery just a tad so that you won't need to call the random() function...

Code: Select all

insert into ColorsRand select subquery.colour from (select colour from Colors order by randomint(100)) as subquery limit 3;
What do you guys think?

PS. Oracle has a nice SAMPLE() function that can be used to grab random rows from a table... Maybe Vertica will implement a similar feature in the future?
Jim Knicely

Image

Note: I work for Vertica. My views, opinions, and thoughts expressed here do not represent those of my employer.

Post Reply

Return to “Vertica SQL”