Select k random rows from postgres django ORM
<p>We have a requirement, that  we want to select k random rows from a database.
So, our intial thought was going like this :-</p>

<pre><code>table.objects.filter(..).order_by('?')[:k]
</code></pre>

<p>but then we read over the internet that this is highly inefficient solution so we came up with this (not so innovative):-</p>

<pre><code>random.sample(table.objects.filter(..), k)
</code></pre>

<p>But this seems to be more slower than previous.</p>

<p>So, we want to know what is correct approach for selection exactly <em>k</em> rows from the database, which in our case is postgres.</p>

<p>Well, if you know roughly the size of your table you can use the new <a href="https://www.postgresql.org/docs/current/static/sql-select.html#SQL-FROM" rel="nofollow">TABLESAMPLE</a> clause to select a percentage of the rows at random. Then, you can always LIMIT it afterwards.</p>

<p>A short blog article covering it <a href="http://blog.2ndquadrant.com/tablesample-in-postgresql-9-5-2/" rel="nofollow">here</a>.</p>

python django postgresql orm