SQL GROUP BY and HAVING Clause

The SQL GROUP BY and HAVING clauses are used to group records from a database table and apply aggregate functions, such as SUM, AVG, and COUNT. They are an important part of any SQL query and allow you to perform data analysis and generate summary reports. GROUP BY is used to group the records, and HAVING is used to filter the groups based on a condition.

GROUP BY

The GROUP BY clause is used to group the records by one or more columns. It is typically used in combination with an aggregate function, such as SUM or AVG. Here is the syntax:

SELECT column1, SUM(column2)
FROM table_name
GROUP BY column1;
    

HAVING

The HAVING clause is used to filter the groups based on a condition. It is similar to the WHERE clause, but is used after the GROUP BY clause. Here is the syntax:

SELECT column1, SUM(column2)
FROM table_name
GROUP BY column1
HAVING SUM(column2) > 100;
    

You can use these clauses in combination with the WHERE clause, JOINs, and other clauses to create complex queries. You can learn more about these and other advanced topics in our SQL tutorials and references.