Open In App

How to divide two columns in SQLAlchemy?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to divide two columns using the SQLAlchemy module of python.

Installing SQLAlchemy

To install SQLAlchemy, run the following command in the terminal.

pip install sqlalchemy pymysql

So, what we have to do in this post is to divide two columns and get output using SQLAlchemy.

Database used:

So, we have the table named “players and what we need to do is to divide the column “score” with the column “matches_played” and get the result. We can do the given task using 2 methods . Both of the methods are as follows. 

Method 1: In this method, what we will do is we will, firstly, connect to the database and then create an SQL query in which we will divide both the columns, then we will execute the query and finally, we will fetch the output.

The SQL query will look like the following:

SELECT column1 / column2 FROM table_name;

Example:

Python3




from sqlalchemy import create_engine
  
user, password, host, database = 'root', '123', 'localhost', 'geeksforgeeks'
engine = create_engine(
    url=f'mysql+pymysql://{user}:{password}@{host}/{database}?charset=utf8')
  
connection = engine.connect()
  
table_name = 'players'
column1 = 'score'
column2 = 'matches_played'
result = connection.execute(f'SELECT {column1} / {column2} FROM {table_name}')
  
for value in result:
    print("Value : ", value)


Note: The value obtained is in a tuple and you can do value[0] (in this case) to get the value and store it directly .

Method 2: This method involves doing the division through python.

The SQL query will look like this:

SELECT column1 , column2 FROM table_name;

Example:

Python3




from sqlalchemy import create_engine
  
user, password, host, database = 'root', '123', 'localhost', 'geeksforgeeks'
engine = create_engine(
    url=f'mysql+pymysql://{user}:{password}@{host}/{database}?charset=utf8')
  
connection = engine.connect()
  
table_name = 'players'
column1 = 'score'
column2 = 'matches_played'
result = connection.execute(f'SELECT {column1} , {column2} FROM {table_name}')
  
for value in result:
    x = value[0] / value[1]
    print("Value : ", x)




Last Updated : 28 Feb, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads