SQLAlchemy - Aggregate Functions
Last Updated :
21 Feb, 2022
In this article, we will see how to select the count of rows using SQLAlchemy using Python.
Before we begin, let us install the required dependencies using pip:
pip install sqlalchemy
Since we are going to use MySQL in this post, we will also install a SQL connector for MySQL in Python. However, none of the code implementations changes with change in the database except for the SQL connectors.
pip install pymysql
There are 5 SQL aggregate functions used often as shown below:
SQL Aggregate FunctionsIn this article, we will cover the examples for each of the above aggregate functions. In both examples, we will count the number of records present in the payment table within the sakila database. The sample record from the payment table looks like:
Payment TableIf you do not have sakila database and want to follow along with this article without installing it then use the SQL script present in the link mentioned below to create the required schema and payment table along with the records. Sakila Payment Table Script
The `func` function in SQLAlchemy is used to implement these aggregate functions. The below table summarizes the method used for each of the aggregate functions.
| SQL Aggregate Function | SQLAlchemy Method |
|---|
| MIN() | sqlalchemy.func.min() |
| MAX() | sqlalchemy.func.max() |
| SUM() | sqlalchemy.func.sum() |
| AVG() | sqlalchemy.func.avg() |
| COUNT() | sqlalchemy.func.count() |
MIN()
Here we will use sqlalchemy.func.min() function to get minimum element for rows.
Syntax: sqlalchemy.select([sqlalchemy.func.min(sqlalchemy.DeclarativeMeta)])
Code:
Python
# IMPORT THE REQUIRED LIBRARY
import sqlalchemy as db
# DEFINE THE ENGINE (CONNECTION OBJECT)
engine = db.create_engine("mysql+pymysql://\
root:password@localhost/sakila")
# CREATE THE METADATA OBJECT TO ACCESS THE TABLE
meta_data = db.MetaData(bind=engine)
db.MetaData.reflect(meta_data)
# GET THE `payment` TABLE FROM THE METADATA OBJECT
payment_table = meta_data.tables['payment']
# SELECT MIN(amount) FROM sakila.`payment`;
query = db.select([db.func.min(payment_table.c.amount)])
# FETCH ALL THE RECORDS IN THE RESPONSE
result = engine.execute(query).first()
# VIEW THE RESULT
print(result[0])
Output:
0.00
MAX()
Here we will use sqlalchemy.func.max() function to get maximum element for rows.
Syntax: sqlalchemy.select([sqlalchemy.func.max(sqlalchemy.DeclarativeMeta)])
Code:
Python
# IMPORT THE REQUIRED LIBRARY
import sqlalchemy as db
# DEFINE THE ENGINE (CONNECTION OBJECT)
engine = db.create_engine("mysql+pymysql://\
root:password@localhost/sakila")
# CREATE THE METADATA OBJECT TO ACCESS THE TABLE
meta_data = db.MetaData(bind=engine)
db.MetaData.reflect(meta_data)
# GET THE `payment` TABLE FROM THE METADATA OBJECT
payment_table = meta_data.tables['payment']
# SELECT MAX(amount) FROM sakila.`payment`;
query = db.select([db.func.max(payment_table.c.amount)])
# FETCH ALL THE RECORDS IN THE RESPONSE
result = engine.execute(query).first()
# VIEW THE RESULT
print(result[0])
 Â
Output:
Â
11.99
SUM()
Â
Here we will use sqlalchemy.func.sum() function to get sum element for rows.
Â
Syntax: sqlalchemy.select([sqlalchemy.func.sum(sqlalchemy.DeclarativeMeta)])
Â
Code:
Â
Python
# IMPORT THE REQUIRED LIBRARY
import sqlalchemy as db
# DEFINE THE ENGINE (CONNECTION OBJECT)
engine = db.create_engine("mysql+pymysql://\
root:password@localhost/sakila")
# CREATE THE METADATA OBJECT TO ACCESS THE TABLE
meta_data = db.MetaData(bind=engine)
db.MetaData.reflect(meta_data)
# GET THE `payment` TABLE FROM THE METADATA OBJECT
payment_table = meta_data.tables['payment']
# SELECT SUM(amount) FROM sakila.`payment`;
query = db.select([db.func.sum(payment_table.c.amount)])
# FETCH ALL THE RECORDS IN THE RESPONSE
result = engine.execute(query).first()
# VIEW THE RESULT
print(result[0])
 Â
Output:
Â
67416.51
AVG()
Â
Here we will use sqlalchemy.func.avg() function to get average element for rows.
Â
Syntax: sqlalchemy.select([sqlalchemy.func.avg(sqlalchemy.DeclarativeMeta)])
Â
Code:
Â
Python
# IMPORT THE REQUIRED LIBRARY
import sqlalchemy as db
# DEFINE THE ENGINE (CONNECTION OBJECT)
engine = db.create_engine("mysql+pymysql://\
root:password@localhost/sakila")
# CREATE THE METADATA OBJECT TO ACCESS THE TABLE
meta_data = db.MetaData(bind=engine)
db.MetaData.reflect(meta_data)
# GET THE `payment` TABLE FROM THE METADATA OBJECT
payment_table = meta_data.tables['payment']
# SELECT AVG(amount) FROM sakila.`payment`;
query = db.select([db.func.avg(payment_table.c.amount)])
# FETCH ALL THE RECORDS IN THE RESPONSE
result = engine.execute(query).first()
# VIEW THE RESULT
print(result[0])
 Â
Output:
Â
4.200667
COUNT()
Â
Here we will use sqlalchemy.func.count() function to get number of rows.
Â
Syntax: sqlalchemy.select([sqlalchemy.func.count(sqlalchemy.DeclarativeMeta)])
Â
Code:
Â
Python
# IMPORT THE REQUIRED LIBRARY
import sqlalchemy as db
# DEFINE THE ENGINE (CONNECTION OBJECT)
engine = db.create_engine("mysql+pymysql://\
root:password@localhost/sakila")
# CREATE THE METADATA OBJECT TO ACCESS THE TABLE
meta_data = db.MetaData(bind=engine)
db.MetaData.reflect(meta_data)
# GET THE `payment` TABLE FROM THE METADATA OBJECT
payment_table = meta_data.tables['payment']
# SELECT COUNT(amount) FROM sakila.`payment`;
query = db.select([db.func.count(payment_table.c.amount)])
# FETCH ALL THE RECORDS IN THE RESPONSE
result = engine.execute(query).first()
# VIEW THE RESULT
print(result[0])
 Â
Output:
Â
16049
Â
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response
In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read