Rechercher dans le manuel MySQL
12.20.1 Aggregate (GROUP BY) Function Descriptions
This section describes group (aggregate) functions that operate on sets of values.
Table 12.26 Aggregate (GROUP BY) Functions
Name | Description |
---|---|
AVG() |
Return the average value of the argument |
BIT_AND() |
Return bitwise AND |
BIT_OR() |
Return bitwise OR |
BIT_XOR() |
Return bitwise XOR |
COUNT() |
Return a count of the number of rows returned |
COUNT(DISTINCT) |
Return the count of a number of different values |
GROUP_CONCAT() |
Return a concatenated string |
JSON_ARRAYAGG() |
Return result set as a single JSON array |
JSON_OBJECTAGG() |
Return result set as a single JSON object |
MAX() |
Return the maximum value |
MIN() |
Return the minimum value |
STD() |
Return the population standard deviation |
STDDEV() |
Return the population standard deviation |
STDDEV_POP() |
Return the population standard deviation |
STDDEV_SAMP() |
Return the sample standard deviation |
SUM() |
Return the sum |
VAR_POP() |
Return the population standard variance |
VAR_SAMP() |
Return the sample variance |
VARIANCE() |
Return the population standard variance |
Unless otherwise stated, group functions ignore
NULL
values.
If you use a group function in a statement containing no
GROUP BY
clause, it is equivalent to grouping
on all rows. For more information, see
Section 12.20.3, “MySQL Handling of GROUP BY”.
Most aggregate functions can be used as window functions. Those
that can be used this way are signified in their syntax
description by
[
,
representing an optional over_clause
]OVER
clause.
over_clause
is described in
Section 12.21.2, “Window Function Concepts and Syntax”, which also includes
other information about window function usage.
For numeric arguments, the variance and standard deviation
functions return a DOUBLE
value.
The SUM()
and
AVG()
functions return a
DECIMAL
value for exact-value
arguments (integer or DECIMAL
),
and a DOUBLE
value for
approximate-value arguments
(FLOAT
or
DOUBLE
).
The SUM()
and
AVG()
aggregate functions do not
work with temporal values. (They convert the values to numbers,
losing everything after the first nonnumeric character.) To work
around this problem, convert to numeric units, perform the
aggregate operation, and convert back to a temporal value.
Examples:
Functions such as SUM()
or
AVG()
that expect a numeric
argument cast the argument to a number if necessary. For
SET
or
ENUM
values, the cast operation
causes the underlying numeric value to be used.
The BIT_AND()
,
BIT_OR()
, and
BIT_XOR()
aggregate functions
perform bit operations. Prior to MySQL 8.0, bit functions and
operators required BIGINT
(64-bit
integer) arguments and returned
BIGINT
values, so they had a
maximum range of 64 bits.
Non-BIGINT
arguments were
converted to BIGINT
prior to
performing the operation and truncation could occur.
In MySQL 8.0, bit functions and operators permit binary string
type arguments (BINARY
,
VARBINARY
, and the
BLOB
types) and return a value of
like type, which enables them to take arguments and produce
return values larger than 64 bits. For discussion about argument
evaluation and result types for bit operations, see the
introductory discussion in Section 12.12, “Bit Functions and Operators”.
AVG([DISTINCT]
expr
) [over_clause
]Returns the average value of
. Theexpr
DISTINCT
option can be used to return the average of the distinct values ofexpr
.If there are no matching rows,
AVG()
returnsNULL
.This function executes as a window function if
over_clause
is present.over_clause
is as described in Section 12.21.2, “Window Function Concepts and Syntax”; it cannot be used withDISTINCT
.Returns the bitwise
AND
of all bits inexpr
.The result type depends on whether the function argument values are evaluated as binary strings or numbers:
Binary-string evaluation occurs when the argument values have a binary string type, and the argument is not a hexadecimal literal, bit literal, or
NULL
literal. Numeric evaluation occurs otherwise, with argument value conversion to unsigned 64-bit integers as necessary.Binary-string evaluation produces a binary string of the same length as the argument values. If argument values have unequal lengths, an
ER_INVALID_BITWISE_OPERANDS_SIZE
error occurs. If the argument size exceeds 511 bytes, anER_INVALID_BITWISE_AGGREGATE_OPERANDS_SIZE
error occurs. Numeric evaluation produces an unsigned 64-bit integer.
If there are no matching rows,
BIT_AND()
returns a neutral value (all bits set to 1) having the same length as the argument values.NULL
values do not affect the result unless all values areNULL
. In that case, the result is a neutral value having the same length as the argument values.For more information discussion about argument evaluation and result types, see the introductory discussion in Section 12.12, “Bit Functions and Operators”.
As of MySQL 8.0.12, this function executes as a window function if
over_clause
is present.over_clause
is as described in Section 12.21.2, “Window Function Concepts and Syntax”.Returns the bitwise
OR
of all bits inexpr
.The result type depends on whether the function argument values are evaluated as binary strings or numbers:
Binary-string evaluation occurs when the argument values have a binary string type, and the argument is not a hexadecimal literal, bit literal, or
NULL
literal. Numeric evaluation occurs otherwise, with argument value conversion to unsigned 64-bit integers as necessary.Binary-string evaluation produces a binary string of the same length as the argument values. If argument values have unequal lengths, an
ER_INVALID_BITWISE_OPERANDS_SIZE
error occurs. If the argument size exceeds 511 bytes, anER_INVALID_BITWISE_AGGREGATE_OPERANDS_SIZE
error occurs. Numeric evaluation produces an unsigned 64-bit integer.
If there are no matching rows,
BIT_OR()
returns a neutral value (all bits set to 0) having the same length as the argument values.NULL
values do not affect the result unless all values areNULL
. In that case, the result is a neutral value having the same length as the argument values.For more information discussion about argument evaluation and result types, see the introductory discussion in Section 12.12, “Bit Functions and Operators”.
As of MySQL 8.0.12, this function executes as a window function if
over_clause
is present.over_clause
is as described in Section 12.21.2, “Window Function Concepts and Syntax”.Returns the bitwise
XOR
of all bits inexpr
.The result type depends on whether the function argument values are evaluated as binary strings or numbers:
Binary-string evaluation occurs when the argument values have a binary string type, and the argument is not a hexadecimal literal, bit literal, or
NULL
literal. Numeric evaluation occurs otherwise, with argument value conversion to unsigned 64-bit integers as necessary.Binary-string evaluation produces a binary string of the same length as the argument values. If argument values have unequal lengths, an
ER_INVALID_BITWISE_OPERANDS_SIZE
error occurs. If the argument size exceeds 511 bytes, anER_INVALID_BITWISE_AGGREGATE_OPERANDS_SIZE
error occurs. Numeric evaluation produces an unsigned 64-bit integer.
If there are no matching rows,
BIT_XOR()
returns a neutral value (all bits set to 0) having the same length as the argument values.NULL
values do not affect the result unless all values areNULL
. In that case, the result is a neutral value having the same length as the argument values.For more information discussion about argument evaluation and result types, see the introductory discussion in Section 12.12, “Bit Functions and Operators”.
As of MySQL 8.0.12, this function executes as a window function if
over_clause
is present.over_clause
is as described in Section 12.21.2, “Window Function Concepts and Syntax”.Returns a count of the number of non-
NULL
values ofexpr
in the rows retrieved by aSELECT
statement. The result is aBIGINT
value.If there are no matching rows,
COUNT()
returns0
.This function executes as a window function if
over_clause
is present.over_clause
is as described in Section 12.21.2, “Window Function Concepts and Syntax”.COUNT(*)
is somewhat different in that it returns a count of the number of rows retrieved, whether or not they containNULL
values.For transactional storage engines such as
InnoDB
, storing an exact row count is problematic. Multiple transactions may be occurring at the same time, each of which may affect the count.InnoDB
does not keep an internal count of rows in a table because concurrent transactions might “see” different numbers of rows at the same time. Consequently,SELECT COUNT(*)
statements only count rows visible to the current transaction.As of MySQL 8.0.13,
SELECT COUNT(*) FROM
query performance fortbl_name
InnoDB
tables is optimized for single-threaded workloads if there are no extra clauses such asWHERE
orGROUP BY
.InnoDB
processesSELECT COUNT(*)
statements by traversing the smallest available secondary index unless an index or optimizer hint directs the optimizer to use a different index. If a secondary index is not present,InnoDB
processesSELECT COUNT(*)
statements by scanning the clustered index.As of MySQL 8.0.14,
InnoDB
supports parallel index reads, which improves performance of non-lockingSELECT COUNT(*) FROM
queries. Thetbl_name
innodb_parallel_read_threads
session variable must be set to a value greater than 1 for parallel index reads to occur. The default value is 4. The actual number of threads used to perform a parallel index read is determined by theinnodb_parallel_read_threads
setting or the number of index subtrees to scan, whichever is smaller. The pages read into the buffer pool during the scan are kept at the tail of the buffer pool LRU list so that they can be discarded quickly when free buffer pool pages are required.Processing
SELECT COUNT(*)
statements takes some time if index records are not entirely in the buffer pool. For a faster count, create a counter table and let your application update it according to the inserts and deletes it does. However, this method may not scale well in situations where thousands of concurrent transactions are initiating updates to the same counter table. If an approximate row count is sufficient, useSHOW TABLE STATUS
.InnoDB
handlesSELECT COUNT(*)
andSELECT COUNT(1)
operations in the same way. There is no performance difference.For
MyISAM
tables,COUNT(*)
is optimized to return very quickly if theSELECT
retrieves from one table, no other columns are retrieved, and there is noWHERE
clause. For example:This optimization only applies to
MyISAM
tables, because an exact row count is stored for this storage engine and can be accessed very quickly.COUNT(1)
is only subject to the same optimization if the first column is defined asNOT NULL
.COUNT(DISTINCT
expr
,[expr
...])Returns a count of the number of rows with different non-
NULL
expr
values.If there are no matching rows,
COUNT(DISTINCT)
returns0
.In MySQL, you can obtain the number of distinct expression combinations that do not contain
NULL
by giving a list of expressions. In standard SQL, you would have to do a concatenation of all expressions insideCOUNT(DISTINCT ...)
.This function returns a string result with the concatenated non-
NULL
values from a group. It returnsNULL
if there are no non-NULL
values. The full syntax is as follows:- [SEPARATOR str_val])
Or:
In MySQL, you can get the concatenated values of expression combinations. To eliminate duplicate values, use the
DISTINCT
clause. To sort values in the result, use theORDER BY
clause. To sort in reverse order, add theDESC
(descending) keyword to the name of the column you are sorting by in theORDER BY
clause. The default is ascending order; this may be specified explicitly using theASC
keyword. The default separator between values in a group is comma (,
). To specify a separator explicitly, useSEPARATOR
followed by the string literal value that should be inserted between group values. To eliminate the separator altogether, specifySEPARATOR ''
.The result is truncated to the maximum length that is given by the
group_concat_max_len
system variable, which has a default value of 1024. The value can be set higher, although the effective maximum length of the return value is constrained by the value ofmax_allowed_packet
. The syntax to change the value ofgroup_concat_max_len
at runtime is as follows, whereval
is an unsigned integer:The return value is a nonbinary or binary string, depending on whether the arguments are nonbinary or binary strings. The result type is
TEXT
orBLOB
unlessgroup_concat_max_len
is less than or equal to 512, in which case the result type isVARCHAR
orVARBINARY
.See also
CONCAT()
andCONCAT_WS()
: Section 12.5, “String Functions”.JSON_ARRAYAGG(
col_or_expr
) [over_clause
]Aggregates a result set as a single
JSON
array whose elements consist of the rows. The order of elements in this array is undefined. The function acts on a column or an expression that evaluates to a single value. ReturnsNULL
if the result contains no rows, or in the event of an error.As of MySQL 8.0.14, this function executes as a window function if
over_clause
is present.over_clause
is as described in Section 12.21.2, “Window Function Concepts and Syntax”.- +------+-----------+-------+
- +------+-----------+-------+
- | 2 | color | red |
- | 2 | fabric | silk |
- | 3 | color | green |
- | 3 | shape | square|
- +------+-----------+-------+
- +------+---------------------+
- | o_id | attributes |
- +------+---------------------+
- | 2 | ["color", "fabric"] |
- | 3 | ["color", "shape"] |
- +------+---------------------+
JSON_OBJECTAGG(
key
,value
) [over_clause
]Takes two column names or expressions as arguments, the first of these being used as a key and the second as a value, and returns a JSON object containing key-value pairs. Returns
NULL
if the result contains no rows, or in the event of an error. An error occurs if any key name isNULL
or the number of arguments is not equal to 2.As of MySQL 8.0.14, this function executes as a window function if
over_clause
is present.over_clause
is as described in Section 12.21.2, “Window Function Concepts and Syntax”.When used as a window function, if there are duplicate keys within a frame, only the last value for the key is present in the result. This is in keeping with the MySQL
JSON
data type specification that does not permit duplicate keys. When parsing text values asJSON
, the value for the last occurring key is retained, and any earlier values are discarded. The value for the key from last row in the frame is deterministic if theORDER BY
specification guarantees that the values have a specific order. If not, the resulting value of the key is nondeterministic.- +------+-----------+-------+
- +------+-----------+-------+
- | 2 | color | red |
- | 2 | fabric | silk |
- | 3 | color | green |
- | 3 | shape | square|
- +------+-----------+-------+
- +------+----------------------------------------+
- | o_id | JSON_OBJECTAGG(attribute, name) |
- +------+----------------------------------------+
- | 2 | {"color": "red", "fabric": "silk"} |
- | 3 | {"color": "green", "shape": "square"} |
- +------+----------------------------------------+
Duplicate key handlingWhen the result of this function is normalized, values having duplicate keys are discarded, and only the last value encountered is used with that key in the returned object (“last duplicate key wins”). This means that the result of using this function on columns from a
SELECT
can depend on the order in which in the rows are returned, which is not guaranteed. Consider the following:- Query OK, 0 rows affected (0.33 sec)
- Query OK, 3 rows affected (0.10 sec)
- +------+------+
- | c | i |
- +------+------+
- +------+------+
- +----------------------+
- | JSON_OBJECTAGG(c, i) |
- +----------------------+
- | {"key": 5} |
- +----------------------+
- Query OK, 3 rows affected (0.08 sec)
- Query OK, 3 rows affected (0.06 sec)
- +------+------+
- | c | i |
- +------+------+
- +------+------+
- +----------------------+
- | JSON_OBJECTAGG(c, i) |
- +----------------------+
- | {"key": 4} |
- +----------------------+
See Normalization, Merging, and Autowrapping of JSON Values, for additional information and examples.
MAX([DISTINCT]
expr
) [over_clause
]Returns the maximum value of
expr
.MAX()
may take a string argument; in such cases, it returns the maximum string value. See Section 8.3.1, “How MySQL Uses Indexes”. TheDISTINCT
keyword can be used to find the maximum of the distinct values ofexpr
, however, this produces the same result as omittingDISTINCT
.If there are no matching rows,
MAX()
returnsNULL
.This function executes as a window function if
over_clause
is present.over_clause
is as described in Section 12.21.2, “Window Function Concepts and Syntax”; it cannot be used withDISTINCT
.For
MAX()
, MySQL currently comparesENUM
andSET
columns by their string value rather than by the string's relative position in the set. This differs from howORDER BY
compares them.MIN([DISTINCT]
expr
) [over_clause
]Returns the minimum value of
expr
.MIN()
may take a string argument; in such cases, it returns the minimum string value. See Section 8.3.1, “How MySQL Uses Indexes”. TheDISTINCT
keyword can be used to find the minimum of the distinct values ofexpr
, however, this produces the same result as omittingDISTINCT
.If there are no matching rows,
MIN()
returnsNULL
.This function executes as a window function if
over_clause
is present.over_clause
is as described in Section 12.21.2, “Window Function Concepts and Syntax”; it cannot be used withDISTINCT
.For
MIN()
, MySQL currently comparesENUM
andSET
columns by their string value rather than by the string's relative position in the set. This differs from howORDER BY
compares them.Returns the population standard deviation of
expr
.STD()
is a synonym for the standard SQL functionSTDDEV_POP()
, provided as a MySQL extension.If there are no matching rows,
STD()
returnsNULL
.This function executes as a window function if
over_clause
is present.over_clause
is as described in Section 12.21.2, “Window Function Concepts and Syntax”.Returns the population standard deviation of
expr
.STDDEV()
is a synonym for the standard SQL functionSTDDEV_POP()
, provided for compatibility with Oracle.If there are no matching rows,
STDDEV()
returnsNULL
.This function executes as a window function if
over_clause
is present.over_clause
is as described in Section 12.21.2, “Window Function Concepts and Syntax”.STDDEV_POP(
expr
) [over_clause
]Returns the population standard deviation of
expr
(the square root ofVAR_POP()
). You can also useSTD()
orSTDDEV()
, which are equivalent but not standard SQL.If there are no matching rows,
STDDEV_POP()
returnsNULL
.This function executes as a window function if
over_clause
is present.over_clause
is as described in Section 12.21.2, “Window Function Concepts and Syntax”.STDDEV_SAMP(
expr
) [over_clause
]Returns the sample standard deviation of
expr
(the square root ofVAR_SAMP()
.If there are no matching rows,
STDDEV_SAMP()
returnsNULL
.This function executes as a window function if
over_clause
is present.over_clause
is as described in Section 12.21.2, “Window Function Concepts and Syntax”.SUM([DISTINCT]
expr
) [over_clause
]Returns the sum of
expr
. If the return set has no rows,SUM()
returnsNULL
. TheDISTINCT
keyword can be used to sum only the distinct values ofexpr
.If there are no matching rows,
SUM()
returnsNULL
.This function executes as a window function if
over_clause
is present.over_clause
is as described in Section 12.21.2, “Window Function Concepts and Syntax”; it cannot be used withDISTINCT
.Returns the population standard variance of
expr
. It considers rows as the whole population, not as a sample, so it has the number of rows as the denominator. You can also useVARIANCE()
, which is equivalent but is not standard SQL.If there are no matching rows,
VAR_POP()
returnsNULL
.This function executes as a window function if
over_clause
is present.over_clause
is as described in Section 12.21.2, “Window Function Concepts and Syntax”.Returns the sample variance of
expr
. That is, the denominator is the number of rows minus one.If there are no matching rows,
VAR_SAMP()
returnsNULL
.This function executes as a window function if
over_clause
is present.over_clause
is as described in Section 12.21.2, “Window Function Concepts and Syntax”.Returns the population standard variance of
expr
.VARIANCE()
is a synonym for the standard SQL functionVAR_POP()
, provided as a MySQL extension.If there are no matching rows,
VARIANCE()
returnsNULL
.This function executes as a window function if
over_clause
is present.over_clause
is as described in Section 12.21.2, “Window Function Concepts and Syntax”.
Document created the 26/06/2006, last modified the 26/10/2018
Source of the printed document:https://www.gaudry.be/en/mysql-rf-group-by-functions.html
The infobrol is a personal site whose content is my sole responsibility. The text is available under CreativeCommons license (BY-NC-SA). More info on the terms of use and the author.
References
These references and links indicate documents consulted during the writing of this page, or which may provide additional information, but the authors of these sources can not be held responsible for the content of this page.
The author This site is solely responsible for the way in which the various concepts, and the freedoms that are taken with the reference works, are presented here. Remember that you must cross multiple source information to reduce the risk of errors.