How to perform arithmetic across columns of a MySQL table using Python?

PythonServer Side ProgrammingProgramming

The arithmetic operations as the name suggests are used to perform the operations such as additon, subtraction,division, multiplication or modulus.

The arithmetic operations are operated on the numeric data in your table.


To perform addition

SELECT op1+op2 FROM table_name

Here, the op1 and op2 are the column names or the numeric values. If the op1 and op2 are the numeric values, then FROM clause are not required.

The + in the above syntax can be replaced by -,*,%,/ to perform other arithmetic operations.

Steps to perform arithmetic operations in a 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

Suppose we have the following table named “Sales”

| sale_price |    tax  |
|    1000    | 200     |
|    500     | 100     |
|    50      | 50      |
|    180     | 180     |


We need to calculate amount adding both the column values including sale_price and the tax.

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


query="SELECT sale_price,tax, concat(sale_price+tax) AS amount FROM Sales"


for row in rows:



( ‘sale_price’ , ‘tax’ , ‘amount’ )

The arithmetic addition is operated on the two columns in the table. Similarly, other arithmetic operations can be performed based on need.

Updated on 10-Jun-2021 13:32:14