Explain the use of MIN() and MAX() using MySQL in Python?

PythonServer Side ProgrammingProgramming

The MIN() and MAX() functions are used to perform arithmetic operations on the columns of the table.

As the name suggests, the MIN() function is used to select and return the samllest value from the selected column.

The MAX() function,on the other hand, selects and returns the highest value from the selected column.

Syntax

MIN()

SELECT MIN(column_name) FROM table_name

MAX()

SELECT MAX(column_name) FROM table_name

Steps invloved in finding minimum and maximum value from a column in table using MySQL in python

  • import MySQL connector

  • establish connection with the connector using connect()

  • create the cursor object using cursor() method

  • create a query using the appropriate mysql statements

  • execute the SQL query using execute() method

  • close the connection

Let us have a table named “Students” which contain the name and marks of the students. We need to find out the lowest and the highest marks of the students. We can use MIN() and MAX() functions in this scenario. The MIN() function operated on the column Marks will give us the lowest marks and MAX() function will return the highest marks.

Students

+----------+-----------+
|    name  |    marks  |
+----------+-----------+
|    Rohit |    62     |
|    Rahul |    75     |
|    Inder |    99     |
|   Khushi |    49     |
|    Karan |    92     |
+----------+-----------+

We need to find the lowest and highest marks from the above table.

Example

import mysql.connector
db=mysql.connector.connect(host="your host", user="your username", password="your
password",database="database_name")

cursor=db.cursor()

query1="SELECT MIN(marks) FROM Students "
cursor.execute(query1)
lowest=cursor.fetchall()
print(“Lowest marks :”,lowest)

query2="SELECT MAX(marks) FROM Students "
cursor.execute(query2)
highest=cursor.fetchall()
print(“Highest marks :”,highest)

db.close()

Output

Lowest marks : 49
Highest marks : 99
raja
Published on 10-Jun-2021 12:57:42
Advertisements