In what situations is it more beneficial to use MySQL's COUNT() function in the query itself instead of relying on rowCount() in PDO?

When dealing with large datasets, it is more beneficial to use MySQL's COUNT() function in the query itself rather than relying on PHP's rowCount() in PDO. This is because using COUNT() in the query allows MySQL to perform the counting operation directly on the database server, resulting in better performance and reduced memory usage. On the other hand, using rowCount() in PDO requires fetching all rows from the result set before counting them, which can be inefficient for large datasets.

// Using MySQL's COUNT() function in the query
$query = "SELECT COUNT(*) FROM table_name WHERE condition = :condition";
$stmt = $pdo->prepare($query);
$stmt->bindParam(':condition', $condition_value);
$stmt->execute();
$count = $stmt->fetchColumn();

echo "Total rows: " . $count;