Random Snippets

  • Home
  • Sequence analysis blog
  • About
  • Categories
    • javascript
    • mysql
    • php
  • Subscribe via RSS

How to randomly order or select rows in a MySQL query

October 28th, 2008  |  Published in mysql

I was looking for a way to order the rows randomly in a MySQL query and the solution was not easy for me to come by. I am posting the solution here in hopes of helping others.

1
2
3
SELECT * 
FROM my_table
ORDER BY RAND()

RAND() returns a random floating-point value but functions to randomly order the selection of rows in the above usage.

If you combine the query with LIMIT, you will end up with a random selection of rows from your table.

1
2
3
4
SELECT * 
FROM my_table
ORDER BY RAND()
LIMIT 3

Assuming you have more than 3 rows in your table, you will always get 3 random rows from the query.

Share with a friend:
    

Customize message


[Slashdot] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Comments or feedback...

If you have any demos that you would like to request, please do so.

Click to cancel reply

Recent Posts

  • Sorting 2D associative arrays in PHP
  • Dynamic or on-the-fly percentage calculations with JavaScript
  • The dangers of embedding the notorious “void(0)” JavaScript code in the href attribute of the “a” tag
  • How to randomly order or select rows in a MySQL query
  • How to convert MySQL timestamp to PHP date type

Recent Comments

  • Anders K on Simulate a button click via JavaScript
  • john on How to find and replace text dynamically via JavaScript
  • Eiolon on How to hide, show, or toggle your div
  • Use label as distant button in HTML – Community – travellin' meets real life on Simulate a button click via JavaScript
  • gaurav on Simulate a button click via JavaScript

Archives

Categories

  • javascript
  • mysql
  • php

©2010 Random Snippets