the SUM function is a basic function of pretty much EVERY SQL server (MySQL, MS SQL Server, DB2, Oracle, etc…)
These are AGGREGATE functions and will only return the single value (unless you use other grouping functions)
It’s better (and generally more efficient) to allow the SQL server to do the math if possible. To illustrate WHY Let’s assume that you have a table of data. with 10 records which have (for example) the Quantity of your product. You want to get the total quantity of items you have.
You could do a query which returns the 10 line items and then sum them up.
Pseudo-Code
<?
if (!$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')) {
echo 'Could not connect to mysql';
exit;
}
if (!mysql_select_db('mysql_dbname', $link)) {
echo 'Could not select database';
exit;
}
$sql = "SELECT quantity FROM table"
$result = mysql_query($sql, $link);
if (!$result) {
echo "DB Error, could not query the databasen";
echo 'MySQL Error: ' . mysql_error();
exit;
}
$tp = 0;
while ($row = mysql_fetch_assoc($result)) {
$tp = $tp + $row['quantity']
}
mysql_free_result($result);
echo $tp;
?>
The above would be able to get the sum of the quantity of records. The problem is that it brought the value of 10 records back. Let’s say that each value represented ONE byte. That would be 10 bytes. Not at problem, right?
Well now let’s expand this to a let’s say a MILLION records (which is not inconceivable). If EACH quantity were only ONE Byte, that would be a Million Bytes that get passed back (and still needs summing).
The summing needs to be done either way whether you do it on the SQL server or in your script. The difference would then be seen in the transfer of data (i.e. a million bytes of data compared to the summed results which once summed may be 2 bytes (a double) of data).
Again, since both script and database are probably on the same server, it’s probably NOT that big of an issue, but this may not always be the case, not to mention you should always try to code it as efficiently as possible.
I hope this helps to clarify things.