Aggregate Functions
- Last Updated: May 15, 2020
- 1 minute read
- DataDirect Connectors
- JDBC
- IBM Db2 5.1
- MySQL 5.1
- Progress OpenEdge 5.1
- SAP Sybase 5.1
- Documentation
The result of a query can be the result of one or more aggregate functions. Aggregate
functions return a single value from a set of rows. An aggregate can be used with a column
name (for example, AVG(salary)) or in combination with a more complex
column expression (for example, AVG(salary * 1.07)). The column expression
can be preceded by the DISTINCT operator. The DISTINCT
operator eliminates duplicate values from an aggregate expression.
The following table describes the supported aggregate functions.
| Aggregate | Returns |
|---|---|
| AVG | The average of the values in a numeric column expression. For
example, AVG(salary) returns
the average of all salary column values. |
| COUNT | The number of values in any column expression. For example,
COUNT(name) returns the
number of name values. When using COUNT with a column name,
COUNT returns the number of non-NULL column values. A special
example is COUNT(*), which returns the number of rows in the set,
including rows with NULL values. |
| MAX | The maximum value in any column expression. For example,
MAX(salary) returns the
maximum salary column value. |
| MIN | The minimum value in any column expression. For example,
MIN(salary) returns the
minimum salary column value. |
| SUM | The total of the values in a numeric column expression. For
example, SUM(salary) returns
the sum of all salary column values. |
Except for COUNT(*), all aggregate functions exclude NULL values. The
returned value type for COUNT is INTEGER and for MIN,
MAX, and AVG it is the same type as the column.
Example A
In this example, only distinct last name values are counted. The default behavior is that
all duplicate values be returned, which can be made explicit with ALL.
COUNT (DISTINCT last_name)
Example B
This example uses the COUNT, MAX, and
AVG aggregate functions:
SELECT
COUNT(amount) AS numOpportunities,
MAX(amount) AS maxAmount,
AVG(amount) AS avgAmount
FROM opportunity o INNER JOIN user u
ON o.ownerId = u.id
WHERE o.isClosed = 'false' AND
u.name = 'MyName'