How to randomly order or select rows in a MySQL query

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. SELECT * 
  2. FROM my_table
  3. 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. SELECT * 
  2. FROM my_table
  3. ORDER BY RAND()
  4. LIMIT 3

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

How to count values with MySQL queries

Let’s say you have the following table called votes that keeps track of how people voted and you want a query to count the number of votes for you instead of having to loop through all the rows with a counter in PHP.

person vote
obama yes
mccain no
obama yes
obama no
mccain yes
obama yes
obama yes
obama no
mccain no

Continue reading How to count values with MySQL queries