3

I want to select a random row from the realm table. Something like -

SELECT * FROM table ORDER BY RANDOM() LIMIT 1;
mihirjoshi
  • 12,161
  • 7
  • 47
  • 78

5 Answers5

5

Something like this would do, yes?

Random random = new Random();
RealmResults<YourTable> list = realm.where(YourTable.class).findAll();
YourTable yourTable = list.get(random.nextInt(list.size()));
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
  • Wouldn't this first read all data. I have 100 thousand records in my table. – mihirjoshi Nov 20 '15 at 14:08
  • 3
    No, RealmResults are lazy-loaded. It is slightly less effective than the SQLite variant because the core still has to do the query, but the memory usage in Java is still only 1 object. – Christian Melchior Nov 20 '15 at 14:20
  • You only execute the query, but you don't actually evaluate the results. You only evaluate 1 random element within that list. So no, this would not read all the data, only 1 data. – EpicPandaForce Nov 20 '15 at 14:26
0

Depends on what you want to do:

Do you want to get a random row from a table? Or A (random) row from a random table?

I guess you mean the former: If you have an id in your table, you could just:

SELECT * FROM table b WHERE id = FLOOR(RAND() * (3 - 0 + 1)) + 0

You should place a min and max here like so:

FLOOR(RAND() * (<max> - <min> + 1)) + <min>

(as found here)

Community
  • 1
  • 1
hclemens
  • 23
  • 1
  • 7
0

SWIFT 5

I do it this way and it works perfect:

let results      = realm.objects(MyObject.self)        // Get all the objects
let randomIndex  = Int.random(in: 0 ..< results.count) // Get a random number within the number of objects returned
let randomObject = results[randomIndex]                // Get a random object
zeeshan
  • 4,913
  • 1
  • 49
  • 58
0

Here's how I do it in .NET, takes 7ms for 70K entries.

    public IEnumerable<Entry> GetRandomEntries()
    {
        var randomizer = new Random();
        var entries = GetRealmInstance().All<Entry>().AsEnumerable();
        // Takes random entries and shuffles them to break the natural order
        var randomEntries = entries
            .OrderBy(x => randomizer.Next(0, DbQueryRandomEntriesLimit))
            .Take(DbQueryRandomEntriesLimit)
            .OrderBy(entry => entry.GetHashCode());

        return randomEntries;
    }

I use AsEnumerable() to allow using .Select in LINQ

Movsar Bekaev
  • 888
  • 1
  • 12
  • 30
-1
String query =String.format("SELECT * FROM realm ORDER BY %d LIMIT 1", random());
databaseHelper = new DatabaseHelper(this);
        database = databaseHelper.getWritableDatabase();
Cursor cursor = database.execSQL(query);

It works assuming that you have a class DatabaseHelper which extends SQLiteOpenHelper

RexSplode
  • 1,475
  • 1
  • 16
  • 24