SQLite - ORDER BY RAND()

53,168

Solution 1

using random():

SELECT foo FROM bar
  WHERE id >= (abs(random()) % (SELECT max(id) FROM bar))
  LIMIT 1;

EDIT (by QOP): Since the docs on SQLite Autoincremented columns states that:

The normal ROWID selection algorithm described above will generate monotonically increasing unique ROWIDs as long as you never use the maximum ROWID value and you never delete the entry in the table with the largest ROWID. If you ever delete rows, then ROWIDs from previously deleted rows might be reused when creating new rows.

The above is only true if you don't have a INTEGER PRIMARY KEY AUTOINCREMENT column (it will still work fine with INTEGER PRIMARY KEY columns). Anyway, this should be more portable / reliable:

SELECT foo FROM bar
  WHERE _ROWID_ >= (abs(random()) % (SELECT max(_ROWID_) FROM bar))
LIMIT 1;

ROWID, _ROWID_ and OID are all aliases for the SQLite internal row id.

Solution 2

SELECT * FROM table ORDER BY RANDOM() LIMIT 1;

Solution 3

Solved:

SELECT * FROM table ORDER BY RANDOM() LIMIT 1;

Solution 4

For a much better performance use this in SQLite:

SELECT * FROM table WHERE id IN (SELECT id FROM table ORDER BY RANDOM() LIMIT x) 

This is also applicable to MySQL. This runs faster because SQL engines first load projected fields of rows to memory then sort them, here we just load and random sort the id field of rows, then we get X of them, and find the whole rows of these X ids which is by default indexed.

Share:
53,168
Alix Axel
Author by

Alix Axel

If you need to, you can contact me at: alix [dot] axel [at] gmail [dot] com. I'm #SOreadytohelp Some of my GitHub repositories: phunction, a minimalistic PHP HMVC Framework. halBox, bash script to bootstrap Debian/Ubuntu servers. ArrestDB, RESTful API for SQLite, MySQL and PostgreSQL databases. genex.js, Genex module for Node.js. If you know how to work with regexes, have a look at http://namegrep.com/. ;)

Updated on July 13, 2020

Comments

  • Alix Axel
    Alix Axel almost 4 years

    In MySQL I can use the RAND() function, is there any alternative in SQLite 3?

  • Emil H
    Emil H almost 15 years
    +1, This is way faster than the other options provided that id is index.
  • Chris Huang-Leaver
    Chris Huang-Leaver almost 15 years
    I disagree. We have two bits of info here now, how to select a single record randomly,how to list all the records randomly. I have never needed to do either, but if I do, now I know how. I also know that MySQL does it different to SQLlite. A super technical question would be more impressive, but less useful.
  • Bill Karwin
    Bill Karwin almost 15 years
    Yes this solution is faster, but assumes id starts at 1 and has no gaps. Otherwise rows that follow gaps are "randomly" chosen more frequently than other rows.
  • Alix Axel
    Alix Axel almost 15 years
    My first thought was that there wasn't any function to order results randomly, or if there was such a feature / function it would be considerable more obscure - that's what happens with SQLite triggers for instance.
  • Lucky
    Lucky over 14 years
    Also the lowest ID will almost never be selected.
  • Louis Waweru
    Louis Waweru about 13 years
    Wow, my query went from >300ms to 1ms!
  • lemontwist
    lemontwist almost 12 years
    And for the record the limit doesn't have to be 1 if you want to order the entire table randomly and access all of the rows in that random order.
  • Cory Trese
    Cory Trese over 10 years
    This will also work if you have a complex WHERE clause and want a random row from that filtered list. The accepted answer does not support that easily.
  • LE GALL Benoît
    LE GALL Benoît over 10 years
    Very good soluce to ge ONLY 1 row randomly, but doesn't work well with a limit bigger than 1 :/ Indeed, I made a test with only 4 inputs im my DDB and a limit of 5 => sometime I have 3 results, sometime 4 results... I think there will be a better random with bigger DDB, but not for the little one.
  • Hitesh Chavda
    Hitesh Chavda over 9 years
    And One More this there is no duplicate row returned in Result, This is what I need (y)
  • sikisis
    sikisis about 9 years
    why I use it has this message of wrong information:1st ORDER BY term does not match any column in the result set
  • osjerick
    osjerick about 5 years
    +1. In my environment this is ~30 times faster compared to SELECT * FROM table ORDER BY RANDOM() LIMIT 1, and still gives true random w/o any requirements to table schema.
  • LarsH
    LarsH about 4 years
    This seems to select one row from the table at random, without trying to randomize the order; whereas the question title is about ORDER BY. In other words this answer doesn't answer the question. Yet it's highly voted and accepted. What gives?
  • Tom
    Tom over 3 years
    Agree. This was at least an order of magnitude faster than 4-5 other queries I found on the web.