The moose likes JDBC and Relational Databases and the fly likes Getting random records Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "Getting random records" Watch "Getting random records" New topic

Getting random records

Kudret Serin
Ranch Hand

Joined: Aug 02, 2005
Posts: 167

Hi all,
How can i get randomly 20 of 600 records from MSSSQL with SELECT statement?
Is there an SQL way?
Thanks in advance
Jeanne Boyarsky
author & internet detective

Joined: May 26, 2003
Posts: 33102

I haven't used MSSQL, but there are two approaches I can think of. You'll need to check whether they are supported.

1) If the database supports random number generation, do an "order by" on that function and then use ROWNUM to return the first 20 rows.
2) Generate 20 random #s in Java between 1 and 600. Then add a clause to the WHERE to only return ROWNUMs matching those.

[OCA 8 book] [Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Other Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, TOGAF part 1 and part 2
Kudret Serin
Ranch Hand

Joined: Aug 02, 2005
Posts: 167

Thanks for the reply

[ April 06, 2007: Message edited by: Kudret Serin ]
I agree. Here's the link:
subject: Getting random records
It's not a secret anymore!