SQL stands for Structured Query Language. It is used to communicate commands to a database server. It is used by databases like MySQL, PostgreSQL, SQL Server, etc. SQL can be used to insert, delete, update, and search database records. In this article, we will discuss HAVING keyword in SQL.
SQL HAVING Clause
The HAVING clause enables users to filter the results based on the groups specified. The SQL HAVING clause is used with the GROUP BY clause. The HAVING clause can be used in tandem with aggregate functions, whereas a WHERE clause cannot be.
Syntax:
SELECT column_name(s)
FROM table_name
WHERE condition
GROUP BY column_name(s)
HAVING condition
ORDER BY column_name(s);
Example - Using SUM Function
Let's look at a SQL HAVING clause example that uses the SUM function.
Consider the following dataset:
The HAVING clause will filter the results to display only those payment_id values with a total amount greater than 10.
Example - Using MIN Function
Let's now see how to use the HAVING clause with the MIN function in MySQL.
You may also use the MIN function to return the client_id and the minimum amount in the client_id. The SQL HAVING clause will return only those client_id where the minimum amount is less than 50.
Example - Using AVG Function
The following statement finds payment_id, whose average amount is greater than 50.
Example - Using MAX Function
Finally, let's look at how you can use the HAVING clause with MySQL's MAX function.
For example, you can also use the MAX function to return the invoice_id and the invoice_id's maximum amount. The MySQL HAVING clause will return only those invoice_id whose maximum amount is greater than 10.
Gain expertise in the latest Business analytics tools and techniques with the Post Graduate Program in Business Analysis. Enroll now!
Conclusion
This brings concludes the SQL HAVING article. We have discussed how the HAVING clause is used with the GROUP BY clause to get more filtered results.
If you are looking to learn more about SQL, then check out our SQL certification course. This certification gives you all of the information you need to begin working with SQL databases and use the database in the applications that you create or use. Learn how to correctly structure your database, author efficient SQL statements, and clauses, and manage your SQL database for scalable growth.
If you have any questions, do let us know in the comments section of the article; our experts will answer them for you at the earliest!