MEDIAN()

Description

MEDIAN() returns the median value of a set of values, that is, returns the value in the middle after sorting a set of values. If the argument set contains an even number of values, the function returns the average of the two numbers in the middle. It can be used as an aggregate or analytical function.

Syntax

  1. > MEDIAN(expr)

Arguments

ArgumentsDescription
exprRequired. Specify the name of the array whose median value is required, whose argument type is a numeric data type or can be implicitly converted to a numeric data type.

Returned Value

The function return value and type are the same as the return value and type of its argument.

Examples

  1. mysql> select median(null);
  2. +--------------+
  3. | median(null) |
  4. +--------------+
  5. | NULL |
  6. +--------------+
  7. 1 row in set (0.00 sec)
  8. drop table if exists t1;
  9. create table t1 (a int,b int);
  10. insert into t1 values (1,null);
  11. mysql> select median(b) from t1;
  12. +-----------+
  13. | median(b) |
  14. +-----------+
  15. | NULL |
  16. +-----------+
  17. 1 row in set (0.01 sec)
  18. insert into t1 values (1,1);
  19. mysql> select median(b) from t1;
  20. +-----------+
  21. | median(b) |
  22. +-----------+
  23. | 1 |
  24. +-----------+
  25. 1 row in set (0.01 sec)
  26. insert into t1 values (1,2);
  27. mysql> select median(b) from t1;
  28. +-----------+
  29. | median(b) |
  30. +-----------+
  31. | 1.5 |
  32. +-----------+
  33. 1 row in set (0.01 sec)
  34. mysql> select median(b) from t1 group by a order by a;
  35. +-----------+
  36. | median(b) |
  37. +-----------+
  38. | 1.5 |
  39. +-----------+
  40. 1 row in set (0.00 sec)
  41. insert into t1 values (2,1),(2,2),(2,3),(2,4);
  42. mysql> select median(b) from t1 group by a order by a;
  43. +-----------+
  44. | median(b) |
  45. +-----------+
  46. | 1.5 |
  47. | 2.5 |
  48. +-----------+
  49. 2 rows in set (0.01 sec)