db_select orderRandom With range I'm trying to query a random node from the last 10 that were created.

So far I've used this but it doesn't produce the right results:

 $query = db_select('node', 'n');
 $query-&gt;fields('n', array('text','created_time'))
   -&gt;orderBy('n.created', 'DESC')
   -&gt;range(0, 10)
   -&gt;orderRandom();
$result = $query-&gt;execute()-&gt;fetchAll();


How can I get the data I want?
The node table doesn't have a text or created_time column so I'm not sure what data you're trying to select. Regardless, here are a couple of examples that use a subquery to select the title and created columns for a single random node from a pool of the ten most recent:


Subquery in the FROM:

$subquery = db_select('node', 'n')
  -&gt;fields('n', ['title', 'created'])
  -&gt;orderBy('n.created', 'DESC')
  -&gt;range(0, 10);

$query = db_select($subquery, 'n2')
  -&gt;fields('n2', ['title', 'created'])
  -&gt;orderByRandom() 
  -&gt;range(0, 1);


Which is roughly equivalent to:

SELECT n2.title, n2.created 
FROM (
  SELECT n.title, n.created
  FROM node n
  ORDER BY n.created DESC
  LIMIT 10
) AS n2
ORDER BY RAND()
LIMIT 1

Subquery in the WHERE:

$subquery = db_select('node', 'n2')
  -&gt;fields('n2', ['nid'])
  -&gt;orderBy('n2.created', 'DESC')
  -&gt;range(0, 10);

$query = db_select('node', 'n')
  -&gt;fields('n', ['title', 'created'])
  -&gt;condition('n.nid', $subquery, 'IN')
  -&gt;orderByRandom()
  -&gt;range(0, 1);


Which is roughly equivalent to:

SELECT n.title, n.created
FROM node n
WHERE n.nid IN (
  SELECT n2.nid
  FROM node n2
  ORDER BY n2.created DESC
  LIMIT 10
)
ORDER BY RAND()
LIMIT 1


And the code:


You could also try a JOIN approach, it's worth trying a few methods to see which has the best performance.