Is there a way to get random N rows from SQL server table? I saw this link, but that is not what I want. I want to get different number of rows each time I run the query - for example, 5 rows, 10 rows etc
Asked
Active
Viewed 73 times
0
-
1`select top (cast(rand() * 10 as int)) * from table`?.. – GSerg Oct 09 '20 at 16:35
-
Please add this as an answer and i will accept it..thanks! – user2543622 Oct 09 '20 at 16:55
-
1At least you need to add the ordering, otherwise you'd be getting the same rows, although different amount of them. – GSerg Oct 09 '20 at 17:04
2 Answers
1
You could use something like this:
select t.*
from (select t.*, row_number() over (order by (select null)) as seqnum
from t
) t cross join
(select count(*) as cnt, rand() as rnd from t) x
where seqnum < cnt * rnd;

Gordon Linoff
- 1,242,037
- 58
- 646
- 786
0
GSerg wrote the following comment:
select top (cast(rand() * 10 as int)) * from table

Peter O.
- 32,158
- 14
- 82
- 96
-
Although there is no guarantee as to which rows are returned when using `top` without `order by`, this hardly seems to return a "random number of _random_ rows". – HABO Nov 13 '20 at 01:58