Skip to content
geeksforgeeks
  • 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
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Database
  • Python MySQL
  • Python SQLite
  • Python MongoDB
  • PostgreSQL
  • SQLAlchemy
  • Django
  • Flask
  • SQL
  • ReactJS
  • Vue.js
  • AngularJS
  • API
  • REST API
  • Express.js
  • NodeJS
Open In App
Next Article:
Python MySQL - Order By Clause
Next article icon

Python MySQL - GROUP BY and HAVING Clause

Last Updated : 29 Aug, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will see how to perform groupby() and HAVING() operations on SQL using Python. Here we will consider a college database to perform group by operation on the department with respect to student strength.

GROUP BY

The GROUP BY statement groups rows that have the same values into single based on the aggregate function used. Aggregate functions are (COUNT(), MAX(), MIN(), SUM(), AVG()).

Syntax: SELECT aggregate_function(column1),column2,...,columnn

FROM table_name

GROUP BY column_name;

Database in use:

Example:

Python3
# Establish connection to MySQL database import mysql.connector   database = mysql.connector.connect(      host="localhost",      user="root",      password="",      database="sravan" )   # Creating cursor object cur_object = database.cursor()   # Execute the query  find = "SELECT  department,sum(strength) from \ college_data GROUP BY(department)"; cur_object.execute(find)   # fetching all results data = cur_object.fetchall()  print("Total departments with count : ") print(" ") for res in data:      print(res[0],res[1],sep="--")   # Close database connection  database.close()  

Output:

GROUP BY Having

Having Clause is basically like the aggregate function with the GROUP BY clause. The HAVING clause is used instead of WHERE with aggregate functions. While the GROUP BY Clause groups rows that have the same values into summary rows. The having clause is used with the where clause in order to find rows with certain conditions. The having clause is always used after the Group By clause.

Syntax: SELECT aggregate_function (column_names),column1,column2,...,columnn FROM table_name

GROUP BY column_name

HAVING aggregate_function(column_name) condition;

Database in use:

Example:

Python3
# Establish connection to MySQL database import mysql.connector   # give connection with xampp database = mysql.connector.connect(      host="localhost",      user="root",      password="",      database="sravan" )   # Creating cursor object cur_object = database.cursor()   find = "SELECT  department,sum(strength) from college_data\ GROUP BY(department) HAVING sum(strength)<=400 ";  # Execute the query  cur_object.execute(find)   # fetching all results data = cur_object.fetchall()  print("Total departments with count less than 400 : ") print(" ") for res in data:      print(res[0],res[1],sep="--")   # Close database connection  database.close()  

Output:


Next Article
Python MySQL - Order By Clause
author
sravankumar_171fa07058
Improve
Article Tags :
  • Python
  • SQL
  • Python-mySQL
Practice Tags :
  • python

Similar Reads

  • Python MySQL - Order By Clause
    A connector is employed when we have to use MySQL with other programming languages. The work of MySQL-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server. OrderBy Clause OrderBy is used to arra
    2 min read
  • Python MySQL - Limit Clause
    A connector is employed when we have to use MySQL with other programming languages. The work of mysql-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and MySQL Server. Python-MySQL-Connector This is a MySQL Con
    2 min read
  • PostgreSQL - GROUP BY clause
    The GROUP BY clause in PostgreSQL is an essential tool that allows us to group rows that share the same values in one or more columns. This powerful functionality is commonly used to perform aggregate calculations such as SUM(), COUNT(), AVG(), and more, enabling us to summarize data efficiently. In
    4 min read
  • Python MariaDB - Order By Clause using PyMySQL
    A MySQL client library is employed when we have to use MySQL with other programming languages. The work of PyMySQL is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server. OrderBy Clause The OrderBy is used
    2 min read
  • Python MySQL - Where Clause
    Where clause is used in MySQL database to filter the data as per the condition required. You can fetch, delete or update a particular set of data in MySQL database by using where clause.Syntax  SELECT column1, column2, .... columnN FROM [TABLE NAME] WHERE [CONDITION];   The above syntax is used for
    2 min read
  • Python MySQL - BETWEEN and IN Operator
    In this article, we are going to see the database operations BETWEEN and IN operators in MySQL using Python. Both of these operators are used with the WHERE query to check if an expression is within a range or in a list of values in SQL. We are going to use the below table to perform various operati
    3 min read
  • How to Query as GROUP BY in Django?
    In Django, the powerful ORM (Object-Relational Mapping) allows developers to interact with databases using Python code. One common database operation is the GROUP BY query, which groups rows sharing a property so that aggregate functions can be applied to each group. This article will guide you thro
    3 min read
  • Group by and count function in SQLAlchemy
    In this article, we are going to see how to perform Groupby and count function in SQLAlchemy against a PostgreSQL database in Python. Group by and count operations are performed in different methods using different functions. Such kinds of mathematical operations are database-dependent. In PostgreSQ
    2 min read
  • Python MySQL - Join
    A connector is employed when we have to use mysql with other programming languages. The work of mysql-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server. Python-MySQL-Connector This is a MySQL
    2 min read
  • Python MariaDB - Limit Clause using PyMySQL
    The Limit clause is used in SQL to control or limit the number of records in the result set returned from the query generated. By default, SQL gives out the required number of records starting from the top but it allows the use of the OFFSET keyword. OFFSET allows you to start from a custom row and
    2 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