[Solved] Why isn\'t RAND() working for doctrine2
Looking to automatically optimize YOUR SQL query? Start for free.

EverSQL Database Performance Knowledge Base

Why isn\'t RAND() working for doctrine2

We had this query on our DB (5 million records)

SELECT *
FROM foo
ORDER BY RAND()
LIMIT 20;

of course it was slow (2.7 seconds)

so we optimized the query to this (instead of ordering 5 million records it picks 100 and orders them):

SELECT *
FROM foo
WHERE RAND() < 0.00001
ORDER BY RAND()
LIMIT 20;

The query time is 0.002 seconds now

For a Symfony2 project we need to get this running on doctrine

public function findAllRandom()
{
   return $this->getEntityManager()
    ->createQuery(
        'SELECT p FROM GabrielUploadBundle:Image p WHERE RAND() < 0.0001 ORDER BY RAND() LIMIT 20')
    ->getResult();
}

But it throws this error

[Syntax Error] line 0, col 48: Error: Expected known function, got 'RAND'

I doesn't seem to know the RAND function

This is a query that would work (if it helps)

   public function findAllRandom()
    {
       return $this->getEntityManager()
        ->createQuery(
            'SELECT p FROM GabrielUploadBundle:Image p WHERE p.upvotes > 3')
        ->getResult();
    }

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Avoid Selecting Unnecessary Columns (query line: 2): Avoid selecting all columns with the '*' wildcard, unless you intend to use them all. Selecting redundant columns may result in unnecessary performance degradation.
The optimized query:
SELECT
        * 
    FROM
        foo 
    ORDER BY
        RAND() LIMIT 20

Related Articles



* original question posted on StackOverflow here.