A few days ago I ran across an interesting post on Stack Overflow, Is there any way to retrieve random row from indexeddb? The posted answer used the following process:

  • Open an index.
  • Iterate over every row.
  • On the first iteration, use the key value as an upper bound, and select a random number from 1 to that number.
  • Iterate until you hit that number.

While this worked, it seemed like a bad idea to iterate over - possibly - a huge number of rows to get to the random row you wanted. I double checked the spec and discovered what seems to be a simpler solution. When you have opened a cursor (and for those who don't know IDB very well, think of it as simply a way to iterate over a table), you can either continue to the next row, continue to a specific key, or use the advance method to go forward a specific number of rows.

I figured advance would be a good way to handle this. I built a simple demo that demonstrates this. I won't bother showing the HTML as it is just two buttons (one to add some seed data and one to select the random value), but you can view source on the linked demo below if you want. Here is the JavaScript. Note - this code can definitely be rewritten to be a bit tighter.

/* global $,document,indexedDB,console */

 * Returns a random integer between min and max
 * Using Math.round() will give you a non-uniform distribution!
function getRandomInt (min, max) {
	return Math.floor(Math.random() * (max - min + 1)) + min;

$(document).ready(function() {
	var db;

	var openRequest = indexedDB.open("randomidb",1);

	openRequest.onupgradeneeded = function(e) {
		var thisDB = e.target.result;

		console.log("running onupgradeneeded");

		if(!thisDB.objectStoreNames.contains("notes")) {
			thisDB.createObjectStore("notes", {autoIncrement:true});

	openRequest.onsuccess = function(e) {
		console.log("running onsuccess");

		db = e.target.result;

		$("#seedButton").on("click", function() {

			var store = db.transaction(["notes"],"readwrite").objectStore("notes");

			for(var i=0; i<10; i++) {
				var note = {
					title:"Just a random note: "+getRandomInt(1,99999),
					created:new Date()

				var request = store.add(note);

				request.onerror = function(e) {
					//some type of error handler

				request.onsuccess = function(e) {
					console.log("Woot! Did it");


		$("#randomButton").on("click", function() {

			//success handler, could be passed in
			var done = function(ob) {
				console.log("Random result",ob);	

			//ok, first get the count
			var store = db.transaction(["notes"],"readonly").objectStore("notes");

			store.count().onsuccess = function(event) {
				var total = event.target.result;
				var needRandom = true;
				console.log("ok, total is "+total);
				store.openCursor().onsuccess = function(e) {
					var cursor = e.target.result;
					if(needRandom) {
						var advance = getRandomInt(0, total-1);
						console.log("going up "+advance);
						if(advance > 0) {
							needRandom = false;
						} else {
					} else {






I assume we can skip the IDB setup and seed functions. I built the bare minimum so I could test the random aspect. The random selection code works by first doing a count on the object store. This returns - yes - the count. Once we have that, we open a cursor that would normally let us iterate over the entire store. On the first iteration it has the first row. We then ask for a random number. Our range starts at 0 because we want to support the first row being acceptable as well. Based on that number we advance X number of rows and return that result to the done function. If for some reason 0 was selected, we run done right away.

Not rocket science, but it seems to work well. At most you run two iterations, not N, so it seems like it should be much more performant than the original answer on Stack Overflow. As I said, this was my first version so the code could definitely be organized a bit better. You can view the demo here: http://www.raymondcamden.com/demos/2014/nov/30/test1.html.