Browsing articles from "December, 2011"

Efficiently Selecting Random Rows From a MySQL Table

Dec 16, 2011   //   by Gor   //   Technical, Work  //  No Comments

It’s tempting to simply use MySQL’s RAND() function to select random records from a table. Consider the following query:

SELECT FLOOR(7 + (RAND() * 5));

However, when considering overhead, this is a rather expensive method to employ. This becomes glaringly apparent when dealing with large datasets.

One effective solution is to select the first and last ids, and let PHP generate the random integer (id).  Then, simply select the record using the random integer.

public function getRandomRecords()
{
	// Select the first id in the target table
	$statement = $this->db->prepare("SELECT some_id
	  FROM table_name
	  ORDER BY some_id ASC LIMIT 1");
	$statement->execute();
	$lowest_id = $statement->fetch(PDO::FETCH_ASSOC);

	// Select the last id in the target table
	$statement = $this->db->prepare("SELECT some_id
	  FROM table_name
	  ORDER BY some_id DESC LIMIT 1");
	$statement->execute();
	$highest_id = $statement->fetch(PDO::FETCH_ASSOC);

	$records_array = array();

	while(true)
	{
	  // Generate a random integer
	  $random_id = rand( $lowest_id['some_id'], $highest_id['some_id'] );

	  // Check to see if the record exists
	  $statement = $this->db->prepare("SELECT col_one, col_two, etc...
		FROM table_name
		WHERE some_id = {$random_id}";
		$statement->execute();
		$result = $statement->fetchAll(PDO::FETCH_ASSOC);

	  // If it exists, add it to the array
	  if($result)
	  {
	    $records_array[] = $record;
	  }

	  $i++;

	  // If the array contains 5 records, stop
	  if(count($records_array) == 5)
	  {
	    break;
	  }
	}

	return $records_array;
}

About Me Stuff

I'm a PHP and Node.js developer, MySQL and MongoDB database designer, web designer, programmer, WordPress developer, graphic designer, musician, and artist… located in Frederick, Maryland.

I am honored and blessed to be the bassist for the Frederick Church of the Brethren's Living Water worship band.

Living Water worships on Sunday mornings at 9:45.