title: Django Query Performance
body: <p>I have a rather performance related question about django queries. </p>
  
  <p>Say I have a table of employees with 10,000 records. Now If I'm looking to select 5 random employees that are of age greater than or equal to 20, let's say some 5,500 employees are 20 or older. The django query would be:</p>
  
  <pre><code>Employee.objects.filter(age__gte=20).order_by('?')[:5]
  </code></pre>
  
  <p>and the raw counterpart of this query in mysql will be:</p>
  
  <pre><code>SELECT * FROM `database`.`employee` 
  WHERE `employee`.`age` &gt;= 20
  ORDER BY RAND ()
  LIMIT 5;
  </code></pre>
  
  <p>From the looks of django query the database first returns the 5,500 records, then python sorts these records on random or whatever order we select and a chunk of first five records is returned whereas the raw query will return only five records from the database directly.</p>
  
  <p>My question is that is there any performance difference between both the queries? If so which one is better and why?</p>