Explain the use of AVG() function in MySQL using Python?

PythonServer Side ProgrammingProgramming

The AVG() function is one of the arithmetic functions in MySQL.

As the name suggests the AVG() function is used to return the average of a numerical column in the table.

Syntax

SELECT AVG(column_name) FROM table_name

Steps you need to follow to use AVG() function on a table using MySQL in python

  • import MySQLl 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

Suppose we have the following table named “Students”.

Students

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

We want to get the average marks obtained by the students.

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 AVG(marks) FROM Students"
cursor.execute(query1)
avg=cursor.fetchall()
print(“Average marks :”,avg)

db.close()

Output

Average marks : 75.4
raja
Published on 10-Jun-2021 13:32:15
Advertisements