DEV Community

Cover image for How to add a condition in SQL with GROUP BY
Maria Yudina
Maria Yudina

Posted on

How to add a condition in SQL with GROUP BY

To add a condition to a GROUP BY clause in SQL, you can use the HAVING keyword. The HAVING keyword is used to specify a condition that must be met by the grouped records.

SELECT statements... GROUP BY column_name1[,column_name2,...] [HAVING condition];
Enter fullscreen mode Exit fullscreen mode

For example, the following query uses the HAVING keyword to only include groups that have a count greater than 1:

SELECT column1, COUNT(*)
FROM table
GROUP BY column1
HAVING COUNT(*) > 1;
Enter fullscreen mode Exit fullscreen mode

This query will group the records in the table by the values in column1 and only include groups that have more than one record. The HAVING clause is typically used together with an aggregate function, such as COUNT or SUM, to check for a condition on the values that are being grouped.

It's important to note that the HAVING clause is used after the GROUP BY clause and it operates on the grouped records, whereas the WHERE clause is used before the GROUP BY clause and it operates on the individual records before they are grouped.

Overall, the HAVING keyword is a useful tool for adding conditions to GROUP BY clauses in SQL.

Top comments (0)