Knowledgebase
MySql Min
This lesson will teach you how to use the aggregate function MIN(). If you missed the Aggregate Introduction Lesson, you might want to check it out to learn about the GROUP BY statement and its use with MySQL aggregate functions.
You can download the table used in this example, products.sql, from our website. A SQL file can be run through your MySQL administrator interface to create the table.
However, if you would like to create the table with PHP/MySQL, check out our Create a MySQL Table and Insert a MySQL Row lessons.
Products Table:
id | name | type | price |
---|---|---|---|
123451 | Park's Great Hits | Music | 19.99 |
123452 | Silly Puddy | Toy | 3.99 |
123453 | Playstation | Toy | 89.95 |
123454 | Men's T-Shirt | Clothing | 32.50 |
123455 | Blouse | Clothing | 34.97 |
123456 | Electronica 2002 | Music | 3.99 |
123457 | Country Tunes | Music | 21.55 |
123458 | Watermelon | Food | 8.73 |
mysql min
The MIN function is an aggregate function that finds the smallest value in a group. The products table that is displayed above has several products of various types. One use of MIN might be to find out the cheapest item in each group.
Just as we did in the Aggregate Introduction Lesson, we are going to GROUP BY type to create four groups: Music, Toy, Clothing and Food. The column that will have the MIN function applied to it is, of course, price.
PHP and MySQL Code:
<?php // Make a MySQL Connection $query = "SELECT type, MIN(price) FROM products GROUP BY type"; $result = mysql_query($query) or die(mysql_error()); // Print out result while($row = mysql_fetch_array($result)){ echo "The cheapest ". $row['type']. " is $" .$row['MIN(price)']; echo "<br />"; } ?>
Display:
The cheapest Food is $8.73
The cheapest Music is $3.99
The cheapest Toy is $3.99