1

How do you select a random rows from a table?

For example, if there are 1000 rows in a table matching the criteria that I want, I want to select just 20 random ones.

Like TOP, but random.

Thanks, and this is for SQL Server CE 3.5!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Meowbits
  • 586
  • 3
  • 9
  • 28

2 Answers2

2

How about this?

 SELECT TOP(20) * FROM myTable ORDER BY NEWID()
BluesRockAddict
  • 15,525
  • 3
  • 37
  • 35
2

How about SELECT * FROM tbl_name ORDER BY RAND() LIMIT 0,20; However if your db is with million rows Both newid() and rand() would perform slow. There is a faster solution .Read this

Milindu Sanoj Kumarage
  • 2,714
  • 2
  • 31
  • 54