In what situations would it be more efficient to let the database handle grouping data instead of PHP?

When dealing with large datasets, it is often more efficient to let the database handle grouping data instead of PHP. This is because databases are optimized for data manipulation and can perform grouping operations much faster than PHP code. By offloading this task to the database, we can reduce the amount of data transferred between the database server and the PHP application, leading to improved performance.

// Example of letting the database handle grouping data instead of PHP
$query = "SELECT category, SUM(quantity) AS total_quantity FROM products GROUP BY category";
$result = mysqli_query($connection, $query);

while($row = mysqli_fetch_assoc($result)) {
    echo "Category: " . $row['category'] . " - Total Quantity: " . $row['total_quantity'] . "<br>";
}