MySQL Forums
Forum List  »  General

Re: select a random row
Posted by: STARYNKEVITCH Basile
Date: January 21, 2005 07:26AM

Julie K Jensen wrote:
> I was wondering if there was a way to select a random row from my database table using mySQL....

I am not a MySQL expert, but if your table has a unique id column (ie INT AUTO_INCREMENT UNIQUE)
named id, you might try

SELECT * FROM mytable WHERE id=CEILING(RAND()*MAX(id))

however, I might be wrong, I did not try this; and it won't be a really random row if you actually deleted rows from your table (in that case, it might return an empty set).

Maybe a better way is to run your pseudo-random generator on the client side (eg in C or PHP, etc..), and repeat a request like

SELECT * FROM mytable WHERE id=$1

where $1 is a pseudo random suitable number, and repeat the above request until it succeeds.

--
Basile STARYNKEVITCH :::: http://starynkevitch.net/Basile/

Options: ReplyQuote


Subject
Written By
Posted
January 20, 2005 01:51PM
Re: select a random row
January 21, 2005 07:26AM
January 21, 2005 03:37PM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.