Learning MySQL By Example
5.1

Aggregate Functions

Aggregate Functions

  • Aggregate functions are synonymous with column functions.
  • A summary query uses at least on column function.
  • AVG, SUM return numeric values.
  • MIN, MAX, COUNT can return numeric, date, or string values
  • All values are included in aggregate functions by default unless you specify the DISTINCT keyword
  • Duplicate rows are excluded in all aggregate functions with the exception of COUNT(*)
  • ***** IF YOU CODE AN AGGREGATE FUNCTION IN THE SELECT STATEMENT, YOU CANNOT ALSO INCLUDE NON-AGGREGATE FUNCTIONS IN THE SELECT STATEMENT UNLESS THOSE NON-AGGREGATE COLUMNS ARE INCLUDED IN A GROUP BY CLAUSE

Table 1. Aggregate Functions List

Aggregate Function

Output data-type

Result

AVG([DISTINCT] column_values)

numeric

The average of the non-null columns in the expression

SUM([DISTINCT] column_values)

numeric

The total of the non-null columns in the expression

MIN([DISTINCT] column_values)

numeric, date, string

The lowest value off the non-null columns in the expression

MAX([DISTINCT] column_values)

numeric, date, string

The highest value of the non-null columns in the expression

COUNT([DISTINCT] column_values)

numeric

The number of the non-null columns in the expression

COUNT(*)

numeric

The number of rows returned by the query

Code Sample:

USE bike;
SELECT AVG(list_price), SUM(list_price), MIN(list_price), 
    MAX(list_price), COUNT(list_price), COUNT(*)
FROM product;

Output:

ag_01.png

CC BY-NC-ND International 4.0

CC BY-NC-ND International 4.0: This work is released under a CC BY-NC-ND International 4.0 license, which means that you are free to do with it as you please as long as you (1) properly attribute it, (2) do not use it for commercial gain, and (3) do not create derivative works.

End-of-Chapter Survey

: How would you rate the overall quality of this chapter?
  1. Very Low Quality
  2. Low Quality
  3. Moderate Quality
  4. High Quality
  5. Very High Quality
Comments will be automatically submitted when you navigate away from the page.
Like this? Endorse it!