Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting random row through SQLAlchemy

How do I select one or more random rows from a table using SQLAlchemy?

like image 695
cnu Avatar asked Sep 13 '08 19:09

cnu


2 Answers

This is very much a database-specific issue.

I know that PostgreSQL, SQLite, MySQL, and Oracle have the ability to order by a random function, so you can use this in SQLAlchemy:

from  sqlalchemy.sql.expression import func, select  select.order_by(func.random()) # for PostgreSQL, SQLite  select.order_by(func.rand()) # for MySQL  select.order_by('dbms_random.value') # For Oracle 

Next, you need to limit the query by the number of records you need (for example using .limit()).

Bear in mind that at least in PostgreSQL, selecting random record has severe perfomance issues; here is good article about it.

like image 178
Łukasz Avatar answered Sep 30 '22 20:09

Łukasz


If you are using the orm and the table is not big (or you have its amount of rows cached) and you want it to be database independent the really simple approach is.

import random rand = random.randrange(0, session.query(Table).count())  row = session.query(Table)[rand] 

This is cheating slightly but thats why you use an orm.

like image 38
David Raznick Avatar answered Sep 30 '22 18:09

David Raznick