SQL Aggregate Functions
The SQL aggregate functions, as their title suggests are used to retrieve minimum and maximum values from a column, to sum values in a column, to get the average of a column values, or to simply count a number of records according to a search condition (or lack of it). We will use the Cars table to show how to use SQL aggregate functions:
CarMake | Model | Year | Color |
Toyota | Camry XLE | 2005 | Gray |
Honda | Accord EX | 2002 | Black |
Lexus | ES 350 | 2008 | Gray |
BMW | 3 Series Coupe | 2008 | Red |
The most commonly used SQL aggregate function is the COUNT function. Here is an example:
The result of this will be the number 2.
You can select minimum and maximum Year from Cars as follows:
The results will be 2002 and 2008 respectively.
You can also select the average Year from the Cars table like this:
The result will be 2005.75, which works out to be 2005 year and 9 months.
Finally you can use the SUM SQL aggregate function to get the sum of values in a certain column:
The result will be 8023, which is not a very useful number as we are summing years, but if we had another column called DollarValue it would have made perfect sense to use SUM to get the total value of our cars for example.