MAX

Sintassi

MAX([DISTINCT] espr)

Spiegazione

Restituisce il valore massimo di espr. MAX() può accettare un argomento stringa; in tal caso, restituisce il massimo argomento stringa. La parola chiave DISTINCT serve a trovare il massimo valore unico di espr, tuttavia produce lo stesso risultato che si ottiene omettendo DISTINCT.

Si noti che i campi SET e ENUM vengono comparati in base al loro valore stringa, non alla posizione nell'insieme, perciò il valore minore letto da MAX() potrebbe essere diverso da quello letto da ORDER BY DESC.

MAX() restituisce NULL se non vi sono righe.

Esempi

CREATE TABLE student (name CHAR(10), test CHAR(10), score TINYINT); 

INSERT INTO student VALUES 
  ('Chun', 'SQL', 75), ('Chun', 'Tuning', 73), 
  ('Esben', 'SQL', 43), ('Esben', 'Tuning', 31), 
  ('Kaolin', 'SQL', 56), ('Kaolin', 'Tuning', 88), 
  ('Tatiana', 'SQL', 87), ('Tatiana', 'Tuning', 83);

SELECT name, MAX(score) FROM student GROUP BY name;
+---------+------------+
| name    | MAX(score) |
+---------+------------+
| Chun    |         75 |
| Esben   |         43 |
| Kaolin  |         88 |
| Tatiana |         87 |
+---------+------------+

Stringa massima:

SELECT MAX(name) FROM student;
+-----------+
| MAX(name) |
+-----------+
| Tatiana   |
+-----------+

Bisogna evitare questo errore comune, perché un raggruppamento non corretto porta a dati non corretti:

SELECT name,test,MAX(SCORE) FROM student;
+------+------+------------+
| name | test | MAX(SCORE) |
+------+------+------------+
| Chun | SQL  |         88 |
+------+------+------------+

Differenza tra ORDER BY DESC e MAX():

CREATE TABLE student2(name CHAR(10),grade ENUM('b','c','a'));

INSERT INTO student2 VALUES('Chun','b'),('Esben','c'),('Kaolin','a');

SELECT MAX(grade) FROM student2;
+------------+
| MAX(grade) |
+------------+
| c          |
+------------+

SELECT grade FROM student2 ORDER BY grade DESC LIMIT 1;
+-------+
| grade |
+-------+
| a     |
+-------+

Commenti

Sto caricando i commenti......
Content reproduced on this site is the property of its respective owners, and this content is not reviewed in advance by MariaDB. The views, information and opinions expressed by this content do not necessarily represent those of MariaDB or any other party.