Contact Our Development Team
Free Code Tutorials & Open Source Code
MySQL - Aggregation
Tutorials > MySQL > Aggregation
Aggregate functions in MySQL
Now that you have completed our MySQL tutorials, you should have learned how to insert, update and delete data from you MySQL tables, along with retrieving it using relationships between tables. Our final guide on MySQL concerns aggregate functions, which allow you to design queries which can provide information you would normally need to use a scripting language to process. First, we need to set up an example table:
`albums` table:
id artist genre title price
67895 Muse Alternative The Resistance 9.99
67896 Paramore Alternative Brand New Eyes 10.99
67897 Jay Z Hip Hop The Blueprint 3 10.99
67898 Dizzie Rascal Hip Hop Tongue 'n' Cheek 7.99
67899 Lethal Bizzle Hip Hop Go Hard 6.99
67900 Chris Rea Rock Still So Far To Go - The Best Of Chris Rea 7.99
67901 Jamie T Rock Kings & Queens 8.99
67902 The Script Rock The Script 8.99
67903 Daughtry Rock Daughtry 8.99
The first aggregate functions we will look at are SUM() and GROUP BY(). SUM adds the values of a columns or group together as an additional return field. GROUP BY creates groups on a column, where rows in that column have the same value. We will also introduce the AS operator, which allows us to create alias names for the additional return fields we create (this is very useful when you start writing large, nested queries)
SELECT `genre`, SUM(`price`) AS `total` FROM `albums` GROUP BY(`genre`)
This query will give us the total price of all items in the table, after they have been split into groups where their `genre` column has the same value. Our results will be:
genre total
Alternative 20.98
Hip Hop 25.97
Rock 34.96
There are a number of aggregate functions which can be used in the same way: AVG(), MIN(), MAX() and COUNT():
SELECT `genre`, MAX(`price`) AS `max` FROM `albums` GROUP BY(`genre`)
SELECT `genre`, MIN(`price`) AS `min` FROM `albums` GROUP BY(`genre`)
SELECT `genre`, AVG(`price`) AS `avg` FROM `albums` GROUP BY(`genre`)
SELECT `genre`, COUNT(`title`) AS `number` FROM `albums` GROUP BY(`genre`)

Max

genre max
Alternative 10.99
Hip Hop 10.99
Rock 8.99

Min

genre min
Alternative 9.99
Hip Hop 6.99
Rock 7.99

Avg

genre avg
Alternative 10.49
Hip Hop 8.657
Rock 8.74

Count

genre number
Alternative 2
Hip Hop 3
Rock 4
Page Responses
Currently there have been no responses to this page...
If you have anything to contribute to this tutorial, found a bug, or know a better way of achieving the same goal, please leave your response below.
     
Copyright ©2009, Wired IDS Ltd. | Licensed under Creative Commons Attribution Share-Alike | Load time: 0.3013 seconds