Open In App

How to Compute the Average of a Column of a MySQL Table Using Python?

A MySQL connector is needed to generate a connection between Python and the MySQL server. Here we will import mysql.connector library to get the average of the specified column in the given database. 

If you need to know how to install MySQL, see How to Install MySQL in Python 3.



Average Function of SQL

SQL AVG() function returns the average of values of a numeric column in a table. It is generally used with the WHERE clause.

AVG() Function Syntax



SELECT AVG(column_name) 
 FROM table_name 
WHERE condition;
 

The following program will help you understand this better.

Database used:

Students Table in school database

Steps to be followed:

Implementation:

Program to find Average using MySQL connector in Python 3.




import mysql.connector
 
# database connection
connection = mysql.connector.connect(
    host="localhost", user="root",
      password="", database="school")
cursor = connection.cursor()
 
# queries for retrievint all rows
retrieve = "Select AVG(Marks) AS average from students;"
 
# executing the queries
cursor.execute(retrieve)
rows = cursor.fetchall()
for i in rows:
    print("Average marks is :" + str(i[0]))
 
 
# committing the connection then closing it.
connection.commit()
connection.close()

Output:

Output of Marks Column Average of Students Table.

Article Tags :