Backend Development 3 min read

How to Efficiently Retrieve Random Rows from MySQL in Laravel

This guide explains three Laravel techniques—native SQL with ORDER BY RAND(), raw expressions, and the inRandomOrder method—to efficiently retrieve a random set of rows from a MySQL database for tasks such as assigning orders or sampling users.

php中文网 Courses
php中文网 Courses
php中文网 Courses
How to Efficiently Retrieve Random Rows from MySQL in Laravel

Laravel often needs to fetch random rows from a MySQL database, for example to assign orders or sample users.

1. Using native SQL MySQL supports ORDER BY RAND() together with LIMIT to select a random subset.

SELECT * FROM table WHERE name="" ORDER BY RAND() LIMIT 100;

In Laravel you can run the same statement with DB::select() :

$info = DB::select('SELECT * FROM table WHERE name="" ORDER BY RAND() LIMIT 100');

2. Using raw expressions Laravel’s query builder allows DB::raw('RAND()') or orderByRaw('RAND()') to achieve the same effect.

$info = self::where('dealing', '<>', '') ->orderBy(DB::raw('RAND()')) ->take(5) ->get();

3. Using the inRandomOrder method Laravel provides inRandomOrder() which automatically adds a random ordering clause.

$info = DB::table('users') ->inRandomOrder() ->take(5) ->get();

For the full article, click the “Read original” link below.

Backend DevelopmentMySQLphpLaravelRandom Data
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.