ORDER BY RAND() slow query workaround for MySQL and Laravel

Опубликовано: 24 Март 2026
на канале: Alex the Web Coder
354
3

In this tutorial we will create 2 alternative queries for ORDER BY RAND() in MySql. Then we'll implement these queries in the Laravel application. These tutorial touches upon such MySql topics as JOIN, UNION, nested subqueries and utilises Eloquent query builder in Laravel.

Installation guide for Laravel:

git clone https://github.com/aloha202/laravel_r... .
Use the "master" branch if you want to follow the tutorial
Use the "rand_workaround" branch if you want to see the final code

In your shell:
php composer install
npm install
npm run build

Set up your database connection and run:
php artisan migrate
php artisan db:seed

Please note that I'm using PHP v.8.1 for this tutorial, but I assume that it will also run seamlessly in the versions 8.0 & 7.x

I'm using "barryvdh/laravel-debugbar" to monitor my SQL-queries in Laravel

You can grab the result queries here: https://snipit.io/public/lists/22253/...

The database with the 50m rows table here: https://github.com/stefanproell/flugh...

Happy coding!

#laravel #php #mysql #sql #webprogramming #programming