ID EN
Miscellaneous Functions

ANY_VALUE(arg)

MySQL 8.4 🇮🇩 Bahasa Indonesia

Fungsi ini berguna untuk kueri GROUP BY ketika mode SQL ONLY_FULL_GROUP_BY diaktifkan, misalnya MySQL menolak kueri yang Anda tahu valid karena alasan yang tidak dapat ditentukan oleh MySQL. Nilai dan tipe pengembalian fungsi sama dengan nilai pengembalian dan tipe argumennya, tetapi hasil fungsi tidak diperiksa untuk mode SQL ONLY_FULL_GROUP_BY.

Syntax

MYSQL
SELECT name, address, MAX(age) FROM t GROUP BY name;
ERROR 1055 (42000): Expression #2 of SELECT list is not in GROUP
BY clause and contains nonaggregated column 'mydb.t.address' which
is not functionally dependent on columns in GROUP BY clause; this
is incompatible with sql_mode=only_full_group_by

Contoh

Example

For example, if name is a nonindexed column, the following query fails with ONLY_FULL_GROUP_BY enabled:

MYSQL
SELECT name, address, MAX(age) FROM t GROUP BY name;
ERROR 1055 (42000): Expression #2 of SELECT list is not in GROUP
BY clause and contains nonaggregated column 'mydb.t.address' which
is not functionally dependent on columns in GROUP BY clause; this
is incompatible with sql_mode=only_full_group_by
Example 2

The failure occurs because address is a nonaggregated column that is neither named among GROUP BY columns nor functionally dependent on them. As a result, the address value for rows within each name group is nondeterministic. There are multiple ways to cause MySQL to accept the query:

MYSQL
SELECT name, ANY_VALUE(address), MAX(age) FROM t GROUP BY name;
Example 3

Alter the table to make name a primary key or a unique NOT NULL column. This enables MySQL to determine that address is functionally dependent on name; that is, address is uniquely determined by name. (This technique is inapplicable if NULL must be permitted as a valid name value.)

MYSQL
SELECT age FROM t GROUP BY age-1;
Example 4

Use ANY_VALUE() to refer to address:

MYSQL
SELECT ANY_VALUE(age) FROM t GROUP BY age-1;
Example 5

In this case, MySQL ignores the nondeterminism of address values within each name group and accepts the query. This may be useful if you simply do not care which value of a nonaggregated column is chosen for each group. ANY_VALUE() is not an aggregate function, unlike functions such as SUM() or COUNT(). It simply acts to suppress the test for nondeterminism.

MYSQL
SELECT name, MAX(age) FROM t;
ERROR 1140 (42000): In aggregated query without GROUP BY, expression
#1 of SELECT list contains nonaggregated column 'mydb.t.name'; this
is incompatible with sql_mode=only_full_group_by
Example 6

Disable ONLY_FULL_GROUP_BY. This is equivalent to using ANY_VALUE() with ONLY_FULL_GROUP_BY enabled, as described in the previous item.

MYSQL
SELECT ANY_VALUE(name), MAX(age) FROM t;