How does using SUM() in a SQL query differ from manually calculating the total sum in PHP code when working with PDO?

When using SUM() in a SQL query, the database server calculates the total sum directly from the database, which can be more efficient and faster than manually calculating it in PHP code. However, when working with PDO, you may need to retrieve the calculated sum from the query result and handle it accordingly in your PHP code.

// Connect to the database using PDO
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare and execute a SQL query to calculate the total sum
$stmt = $pdo->prepare("SELECT SUM(column_name) AS total_sum FROM your_table");
$stmt->execute();

// Fetch the total sum from the query result
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$totalSum = $result['total_sum'];

// Use the total sum in your PHP code as needed
echo "Total sum: " . $totalSum;