VOOZH about

URL: https://www.geeksforgeeks.org/python/python-mysql-group-by-and-having-clause/

⇱ Python MySQL - GROUP BY and HAVING Clause - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Python MySQL - GROUP BY and HAVING Clause

Last Updated : 29 Aug, 2022

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:

👁 Image

Example:

Output:

👁 Image

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:

👁 Image

Example:

Output:

👁 Image

Comment
Article Tags:
Article Tags: