Skip to content
PHP Logo

Are there any potential compatibility issues with using ORDER BY RAND() in older versions of MySQL with PHP?

When using ORDER BY RAND() in older versions of MySQL with PHP, there can be potential performance issues as it can be slow on large datasets. One way to solve this is by using a combination of RAND() and a unique identifier column in the table to achieve random ordering without the performance drawbacks.

php
// Connect to the database
$connection = new mysqli("localhost", "username", "password", "database");

// Query to select rows with random ordering
$query = "SELECT * FROM table_name ORDER BY RAND(), id";

// Execute the query
$result = $connection->query($query);

// Fetch and display the results
while($row = $result->fetch_assoc()) {
    echo $row['column_name'] . "<br>";
}

// Close the connection
$connection->close();