cjds
cjds

Reputation: 8426

SQL query to get random entries

Lets say I have a table T.

And T contains X tuples. (And table T has a numeric PRIMARY KEY)

Is there a way in SQL to get a random subset(n) of these tuples.

That is every time I run the query a different group of tuples is output.

(Note: I know it can be done via the programming language but that would mean running N queries to my database).

The only solution I could come up with was

1.generate n unique random numbers in an array(arr)

2.Add the numbers in a loop as

  "SELECT * FROM T where id="+arr[0] + "OR id=" +arr[1].....+"OR id="+arr[n]

AND I'M USING A PHPMYADMIN database

But this seems unelegent to me.Thoughts?

Thanks

Upvotes: 0

Views: 84

Answers (1)

Joe Green
Joe Green

Reputation: 1777

SELECT * FROM T ORDER BY RAND() LIMIT 5

Upvotes: 2

Related Questions