randomize SELECT

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
HormonX
Forum Commoner
Posts: 50
Joined: Tue Dec 10, 2002 7:43 pm
Location: Toronto

randomize SELECT

Post by HormonX »

Is there a way to select random rows from a db using MySQL query string ?

Greg
User avatar
scorphus
Forum Regular
Posts: 589
Joined: Fri May 09, 2003 11:53 pm
Location: Belo Horizonte, Brazil
Contact:

Post by scorphus »

Although not most elegant/correct solution, this works:

Code: Select all

SELECT *, rand() AS rnd FROM test_table ORDER BY rnd LIMIT 1;
I hope this works for you.

-- Scorphus
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

it doesn't require aliasing rand to anything, but can help if you'd like to know how they were selected. For example:

Code: Select all

SELECT * FROM table_name ORDER BY RAND()
typically works as well.
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post by timvw »

[to make sure codd wouldn't turn in his grave :p]
the returned rows from a query are per definition unordered/in a random order if there is not a order by clause in the query.
Post Reply