MySQL databse system has a number of built-in functions that allow you to write less code and do less code and in this tutorial we’ll look at MySQL SUM and MySQL MAX fucntiosn. As a web developer, I work with the MySQL database quite extensively and every time, I’d like to make leverage the resources provided by a system. Over the years MySQL has improved a lot and now it’s the leading database used together with PHP to power websites. In this tutorial, I’ll demonstrate how to leverage MySQL SUM and MySQL MAX functions to quickly calculate and retrieve data. We’ll refer to this MySQL table I created for this tutorial. Take a note of the product_price and product_quantity columns as those will be relevant to our discussion.

MySQL SUM:

This function allows you to get the sum of values from a particular column. In the following code snippet we’ll retrieve the sum quantity of all products from our table above.

$query = "SELECT SUM(product_quantity) FROM products";
$result = mysql_query($query) OR die(mysql_error());
while($row = mysql_fetch_array($result)) {
	echo "Total number of products is " . $row['SUM(product_quantity)'];
}

MySQL MAX:

The MAX function works in a similar way. MySQL MAX function is used to retrieve the largest value from a table column. In fact you can just substitute the SUM above for MAX and it’ll work fine. In the following code, I query the database for the cost of the most expensive product:

$query = "SELECT MAX(product_price) FROM products";
$result = mysql_query($query) OR die(mysql_error());
while($row = mysql_fetch_array($result)) {
	echo "Most expensive product costs " . $row['MAX(product_price)'];
}

I hope this tutorial has been of help to you. Please spread some love by clicking on one of this buttons below to share with your audience.