When is the right time to optimize queries for performance, considering the trade-off with code readability?

Optimizing queries for performance should be done when the application experiences noticeable slowdowns or when dealing with large datasets. It is important to strike a balance between performance optimization and code readability. If the query optimization significantly impacts code readability, it might be better to prioritize readability unless performance is severely impacted.

// Example of optimizing a query for performance
$query = "SELECT * FROM users WHERE status = 'active' ORDER BY created_at DESC LIMIT 10";
$result = mysqli_query($connection, $query);

// Process the query result
if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        // Handle each row of data
    }
}