Are there best practices for optimizing PHP scripts that involve sorting database queries?

When sorting database queries in PHP, it's important to optimize the query itself by using appropriate indexes and limiting the amount of data retrieved. Additionally, you can optimize the PHP script by minimizing unnecessary loops or iterations and utilizing built-in sorting functions.

// Example of optimizing PHP script for sorting database queries

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

// Query the database with sorting
$query = "SELECT * FROM table_name ORDER BY column_name";
$result = $connection->query($query);

// Fetch and display the sorted results
while ($row = $result->fetch_assoc()) {
    // Process and display the data
}

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