If you're using PostgreSQL 9.5+, you can take advantage of TABLESAMPLE
to select a random record.
The two default sampling methods (SYSTEM
and BERNOULLI
) require that you specify the number of rows to return as a percentage of the total number of rows in the table.
-- Fetch 10% of the rows in the customers table.
SELECT * FROM customers TABLESAMPLE BERNOULLI(10);
This requires knowing the amount of records in the table to select the appropriate percentage, which may not be easy to find quickly. Fortunately, there is the tsm_system_rows
module that allows you to specify the number of rows to return directly.
CREATE EXTENSION tsm_system_rows;
-- Fetch a single row from the customers table.
SELECT * FROM customers TABLESAMPLE SYSTEM_ROWS(1);
To use this within ActiveRecord, first enable the extension within a migration:
class EnableTsmSystemRowsExtension < ActiveRecord::Migration[5.0]
def change
enable_extension "tsm_system_rows"
end
end
Then modify the from
clause of the query:
customer = Customer.from("customers TABLESAMPLE SYSTEM_ROWS(1)").first
I don't know if the SYSTEM_ROWS
sampling method will be entirely random or if it just returns the first row from a random page.
Most of this information was taken from a 2ndQuadrant blog post written by Gulcin Yildirim.