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:

CarMakeModelYearColor
ToyotaCamry XLE2005Gray
HondaAccord EX2002Black
LexusES 3502008Gray
BMW3 Series Coupe2008Red

The most commonly used SQL aggregate function is the COUNT function. Here is an example:

SELECT COUNT(*) FROM Cars WHERE Color = 'Gray';

The result of this will be the number 2.

You can select minimum and maximum Year from Cars as follows:

SELECT MIN(Year) FROM Cars;


SELECT MAX(Year) FROM Cars;

The results will be 2002 and 2008 respectively.

You can also select the average Year from the Cars table like this:

SELECT AVG(Year) FROM Cars;

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:

SELECT SUM(Year) FROM Cars;

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.