Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
SQLAlchemy - Aggregate Functions
Next article icon

SQLAlchemy - Aggregate Functions

Last Updated : 21 Feb, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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 Functions

In 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 Table

If 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 FunctionSQLAlchemy 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


 


Next Article
SQLAlchemy - Aggregate Functions

A

apathak092
Improve
Article Tags :
  • Python
  • Python-SQLAlchemy
Practice Tags :
  • python

Similar Reads

    SQLAlchemy Core - Functions
    SQLAlchemy provides a rich set of functions that can be used in SQL expressions to perform various operations and calculations on the data. SQLAlchemy provides the Function API to work with the SQL functions in a more flexible manner. The Function API is used to construct SQL expressions representin
    7 min read
    MySQL Aggregate Function
    MySQL Aggregate Functions are used to calculate values from multiple rows and return a single result, helping in summarizing and analyzing data. They include functions for counting, summing, averaging, and finding maximum or minimum values, often used with the GROUP BY clause. In this article, we wi
    3 min read
    PL/SQL Aggregate Function
    In PL/SQL, aggregate functions play an important role in summarizing and analyzing data from large datasets. These built-in SQL functions perform calculations on a set of values and return a single result, making them invaluable for tasks like calculating totals, averages, and identifying the highes
    5 min read
    SQLAlchemy - Introduction
    SQLAlchemy is basically referred to as the toolkit of Python SQL that provides developers with the flexibility of using the SQL database. The benefit of using this particular library is to allow Python developers to work with the language's own objects, and not write separate SQL queries. They can b
    3 min read
    SQLAlchemy Core - Joins
    SQLAlchemy Core is a Python toolkit that enables developers to create complex database applications. It provides several features, one of which is the ability to join tables.  Joining tables allows developers to retrieve data from multiple tables simultaneously, which is useful when the data is rela
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences