Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

frezno's avatar
Level 36

selecting a random number of entries

i want to select a limited number of random entries from the database.
with pure sql pretty much a no-brainer:

select * from table
order by rand()
limit(10)

using the query builder it doesn't work. rand() is not being accepted:

DB::table('table')
->orderBy(rand())
->limit(10)

using orderByRaw doesn't work either (at least not the ways i tried it)

Any ideas how i get a limited random number of entries out of the table?

0 likes
3 replies
RachidLaasri's avatar
Level 41
DB::table('table')->orderBy(DB::raw('RAND()'))->take(10)->get();
1 like
Penderis's avatar

Think you need to pass the rand operator a min and max value, assuming nothing returned because rand() on its own generates numbers far larger than rows contained.

frezno's avatar
Level 36

thank you, @RachidLaasri , after searching for quite some time i just found the same solution as you mentioned.
i know, rand() ist not very efficient. it's to get started.

Update:
orderByRaw() is working as well - forgot to quote it:

->orderByRaw('RAND()')

might be a little nicer

Please or to participate in this conversation.