Random sorting

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
d3ad1ysp0rk
Forum Donator
Posts: 1661
Joined: Mon Oct 20, 2003 8:31 pm
Location: Maine, USA

Random sorting

Post by d3ad1ysp0rk »

Been searching forever (google, mysql.com, etc etc), and my question is so easy I can't believe I haven't found it yet..

I want to pick a random list of values from my table, so, is there any sql like this:
"SELECT * FROM `table` ORDER BY rand";

i believe thats what it was, im just not sure.. so is there a "random" order by clause?

thanks.
microthick
Forum Regular
Posts: 543
Joined: Wed Sep 24, 2003 2:15 pm
Location: Vancouver, BC

Re: Random sorting

Post by microthick »

LiLpunkSkateR wrote:Been searching forever (google, mysql.com, etc etc), and my question is so easy I can't believe I haven't found it yet..

I want to pick a random list of values from my table, so, is there any sql like this:
"SELECT * FROM `table` ORDER BY rand";

i believe thats what it was, im just not sure.. so is there a "random" order by clause?

thanks.
You've almost got it.

For MySQL:

select * from table order by rand()

You can also limit to however many random records you want.

For example, for a random tip of the day:

select tipid, tiptitle, tipbody from tips order by rand() limit 1


For MS-SQL Server, it's very similar:

select * from table order by newid()

Or, again for the tip of the day:

select top 1 tipid, tiptitle, tipbody from tips order by newid()
Post Reply