PHP MySQL tutorial

Max and Min Functions in MySQL

This article explains how we can calculate maximum and minimum value of all the values in a particular column.To do so, MAX() and MIN() functions are used in MySQL.

The MAX() function

SELECT MAX(column)
FROM table;

To find maximum of all the values in a particular column using MAX function in MySQLi, pass the query for finding maximum values to the query function of the mysqli object. The following example finds maximum of all the ages in the patient_age column of patient table.




Using MAX Function in Mysqli



connect_error) {
    die("Connection not established: " . $connection->connect_error);
} 
    
$query = "Use Hospital;";
$connection->query($query);
    
// Using MAX Function

$query = "SELECT MAX(patient_age) ".
"FROM Patient ";
$output = $connection->query($query);

if ($output->num_rows > 0) {
    // output data of each row
    while($row = $output->fetch_assoc()) {
        echo "Maximum age is " . $row["MAX(patient_age)"]."
"; } } else { echo "0 results"; } $connection->close(); ?>

Download the code

Using MIN() function in MySQL

The syntax of MIN function is as followsL

SELECT MIN(column)
FROM table;

To find minimum of all the values in a particular column using MIN function in MySQLi, pass the query for finding maximum values to the query function of the mysqli object. The following example finds minimum of all the ages in the patient_age column of patient table.




Using MIN Function in Mysqli



connect_error) {
    die("Connection not established: " . $connection->connect_error);
} 
    
$query = "Use Hospital;";
$connection->query($query);
    
// Using MIN Function

$query = "SELECT MIN(patient_age) ".
"FROM Patient ";
$output = $connection->query($query);

if ($output->num_rows > 0) {
    // output data of each row
    while($row = $output->fetch_assoc()) {
        echo "Minimum age is " . $row["MIN(patient_age)"]."
"; } } else { echo "0 results"; } $connection->close(); ?>

Download the code

<<< Selecting Limited records via LIMIT in MySQLSUM and AVG Functions in MySQL >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .