In what situations would it be preferable to handle grouping and subtotal calculations directly in the database query rather than in PHP code?

When dealing with large datasets, it is preferable to handle grouping and subtotal calculations directly in the database query rather than in PHP code. This is because performing these calculations in the database can be more efficient and faster, as the database engine is optimized for such operations. By letting the database handle these calculations, you can reduce the amount of data that needs to be transferred between the database and the PHP application, leading to improved performance.

// Example of handling grouping and subtotal calculations directly in the database query

$query = "SELECT category, SUM(price) AS total_price
          FROM products
          GROUP BY category";

$result = mysqli_query($connection, $query);

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