SQL MIN Command

Min Query Minimum value in a numeric field can be collected by applying MIN() SQL command.
We will try MIN sql command and how to use it in our tables. But the best way to use MIN command is to apply it in a numeric field.Here is our table with all the records.

id name class mark
1 John Deo Four 75
2 Max Ruin Three 85
3 Arnold Three 55
4 Krish Star Four 60
5 John Mike Four 60
6 Alex John Four 55
 
You can check SQL MAX command to get maximum or highest value of a range of records.

We will apply the MIN command here like this to the field  mark
SELECT MIN( mark ) FROM `student`
MIN(mark)
55
The command will locate the minimum  value of the mark field and return. We can define some header  like this also.
SELECT MIN(mark) as min_mark FROM `student`
min_mark
55

Minimum mark in each class

Now let us find out what is the minimum mark ( or lowest ) in each class. Here we can use the Group By command to find out the minimum mark obtained by each class
SELECT class, min( mark ) as min_mark FROM `student` GROUP BY class
class min_mark
Four 55
Three 55

Here  minimum mark of each class is displayed. Since we have two class in our table so the sql command has returned two class with lowest mark in each of them. We have to use Group By clause if we ask for the query to return any other field name other than the min. Otherwise system will generate error.

Getting all the details of the record having minimum ( min ) data

Among the students who got the minimum mark? This is done by using SQL Sub query. Like this .
SELECT * FROM `student` WHERE mark=(select min(mark) from student)
Output is here
idnameclassmark
6Alex JohnFour55

Using SQL with MIN Query in PHP Script

Query using PHP script First we will connect to MySQL database.

Here is the sample code.
<?Php
require "config.php";

$count="SELECT class, MIN( mark ) as min_mark FROM `student` GROUP BY class";

echo "<table>";
echo "<tr><th>class</th><th>max_mark</th></tr>";
foreach ($dbo->query($count) as $row) {
echo "<tr ><td>$row[class]</td><td>$row[min_mark]</td></tr>";
}
echo "</table>";
?>


SQL Math References Maximum value Query
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com
    hmds

    04-08-2011

    This is great, but how would you go about getting the id of the student with the lowest mark in each class in this case. So, to return id class min_mark 3 Four 55 6 Three 55
    Avinash Kumar

    21-05-2012

    select name,price from table where price=(select min(price) from table);
    smo1234

    26-04-2019

    test after removal of js file

    Post your comments , suggestion , error , requirements etc here





    SQL Video Tutorials










    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2023 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer