Joined August 2012
·

Mark Selby

Manila, Barcelona, London
·
·

Posted to Rails Quick Tips - Random Records over 1 year ago

If you have large tables in Postgres, you can utiilise a fast stats based count and use that as the offset like so :

SELECT * FROM mytable OFFSET (random() * (SELECT reltuples::bigint AS estimate FROM pgclass WHERE relname='my_table')) LIMIT 1;

So, total rows for a table : SELECT reltuples::bigint AS estimate FROM pgclass WHERE relname='mytable'

You would need to -minus the total rows with the same number as the LIMIT.

The biggest poisions in Rails are seeding a few records and Active Record. It means that development is done with data that doesn't show the horrific performance problems until pushed to Production, at which point all panic breaks loose and developers who are then unused to SQL have to try to understand the problem they created.

Achievements
29 Karma
0 Total ProTip Views
Interests & Skills