Bookmark and Share

MySQL Aggregate Functions - COUNT()

This lesson will teach you how to use the aggregate function COUNT(). If you missed the Aggregate Introduction Lesson, please check it out now, as it explains many concepts used in this lesson!

Advertise on Tizag.com

We will be using the "products" table that we constructed to display the use of MySQL's COUNT function.

You can download the products.sql file from our website. If you are new to MySQL you will need to know how to Create a MySQL Table and Insert a MySQL Row first.

Below is the MySQL table "products".

Products Table:

idnametypeprice
123451Park's Great HitsMusic19.99
123452Silly PuddyToy3.99
123453PlaystationToy89.95
123454Men's T-ShirtClothing32.50
123455BlouseClothing34.97
123456Electronica 2002Music3.99
123457Country TunesMusic21.55
123458WatermelonFood8.73

MySQL COUNT - Counting Records

The COUNT function is an aggregate function that simply counts all the items that are in a group. The "products" table that is displayed above has several products of various types. One use of COUNT might be to find out how many items of each type there are in the table.

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. For a slight change of pace, let's count the name column to find how many products there are per type.

PHP and MySQL Code:

<?php
// Make a MySQL Connection

$query = "SELECT type, COUNT(name) FROM products GROUP BY type"; 
	 
$result = mysql_query($query) or die(mysql_error());

// Print out result
while($row = mysql_fetch_array($result)){
	echo "There are ". $row['COUNT(name)'] ." ". $row['type'] ." items.";
	echo "<br />";
}
?>

Display:

There are 2 Clothing items.
There are 1 Food items.
There are 3 Music items.
There are 2 Toy items.
Bookmark and Share




Download Tizag.com's MySQL Book

If you would rather download the PDF of this tutorial, check out our MySQL eBook from the Tizag.com store. You may also be interested in getting the PHP eBook

Found Something Wrong in this Lesson?

Report a Bug or Comment on This Lesson - Your input is what keeps Tizag improving with time!

Advertise Here

More Tutorials!
Microsoft Office Tutorials Artist Tutorials