MySQL: Return random row

For habere.ch, we launched a contest where we award a restaurant voucher to a random person that wrote a review of a restaurant on our site. For this, we will be using the following query:

SELECT DISTINCT comment_author,comment_author_email
FROM wp_comments
ORDER BY RAND()
LIMIT 1;

What this query does is, that it selects all distinct rows, orders them randomly and shows the first entry of this selection.

Note that this query is relatively slow and should not be used in a program. When you use EXPLAIN on this query, MySQL will explain to you that it will create a temporary table and run a sort. Then only one entry is returned. But when you just use it once to determine a winner, this will work just fine!

Hello world

My name is Simon Krenger, I am a Technical Account Manager (TAM) at Red Hat. I advise our customers in using Kubernetes, Containers, Linux and Open Source.

Elsewhere

  1. GitHub
  2. LinkedIn
  3. GitLab