Is it possible to fetch 10 random records from database using only pure Ecto queries, and not on application side? For example, I'm don't want to get all records from the database and then take random values from them in Elixir (like this):
Subscribers
|> Repo.all
|> Enum.take_random(10)
Ecto doesn't provide a generic random
function for retrieving records, because the underlying databases/schemas can (and do) implement it in very different ways.
But if you know what database you're dealing with, you can use fragment/1
and limit/3
to achieve that. For postgresql, you can use them with the RANDOM()
function:
import Ecto.Query
query =
from Subscribers,
order_by: fragment("RANDOM()"),
limit: 10
Repo.all(query)
This is equivalent to calling this sql
query:
SELECT * FROM subscribers ORDER BY RANDOM() LIMIT 10
I found this question trying to figure out how to grab a single random record that has a nil parent_task property.
thought I'd post my solution incase it helps anyone.
if someone knows how to avoid doing List.first and only use Ecto queries I'd appreciate a comment!
query =
from t in Subscriber,
where: is_nil(t.parent_task),
order_by: fragment("RANDOM()"),
limit: 1
Repo.all(query) |> List.first
Repo.all(Subscriber) |> Enum.filter(fn x -> is_nil(x.parent_task) end) |> Enum.random()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With