How to Get the Minimum and maximum Value of a Column of a MySQL Table Using Python?
Prerequisite: Python: MySQL Create Table
In this article, we are going to see how to get the Minimum and Maximum Value of a Column of a MySQL Table Using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector-Python module is an API in python for communicating with a MySQL database.
Database in use:
We are going to use Beginner(Database name) database and table describing the salary.
Approach:
- Import module.
- Make a connection request with the database.
- Create an object for the database cursor.
- Execute the following MySQL query:
SELECT MIN(Column_name) AS minimum FROM Table_name. SELECT MAX(Column_name) AS minimum FROM Table_name.
- And print the result.
Example 1: Getting the minimum value of a column.
Python3
# Establish connection to MySQL database import mysql.connector mydb = mysql.connector.connect( host = "localhost" , user = "root" , password = "root123" , database = "Beginner" ) # Create a cursor object cursor = mydb.cursor() # Execute the query cursor.execute( "SELECT MIN(Value) AS minimum FROM salary" ) result = cursor.fetchall() for i in result: maximum = float (i[ 0 ]) print (maximum) # Close database connection mydb.close() |
Output:
200.0
Example 2: Getting the maximum value of a column.
Python3
# Establish connection to MySQL database import mysql.connector mydb = mysql.connector.connect( host = "localhost" , user = "root" , password = "root123" , database = "Beginner" ) # Create a cursor object cursor = mydb.cursor() cursor.execute( "SELECT MAX(Value) AS maximum FROM salary" ) result = cursor.fetchall() for i in result: maximum = float (i[ 0 ]) print (maximum) # Close database connection mydb.close() |
Output:
350030.0
Contact Us