![]() |
In MySQL, the HAVING clause is used in conjunction with the GROUP BY clause to filter the results of a query based on aggregate functions. It provides a way to apply conditions to the grouped results, which cannot be achieved using the WHERE clause alone. The HAVING clause is essential when you need to filter groups of data that are returned by a GROUP BY query. Unlike the WHERE clause, which filters rows before grouping, the HAVING clause filters groups after the aggregation has been performed. MySQL HAVING ClauseThe Syntax:SELECT column1, column2, AGGREGATE_FUNCTION(column_name) Where:
Demo MySQL DatabaseTo get a good understanding of the HAVING Clause, we’ll first create a sample database and table, then run some queries to see how the HAVING Clause works. Let’s create a table named sales with the following sample data: CREATE TABLE sales ( Output: ![]() Output Examples of MySQL HAVING ClauseExample 1: Filtering Groups by CountIn this example we will the find products that have been sold more than once. SELECT product, COUNT(*) Output: +---------+----------+ Explanation: Laptop appears twice in the table (Laptop with id 1 and 3) and Mouse appears three times in the table (Mouse with id 2, 4, and 7). Products that appear only once (like Keyboard and Headphones) are not included in the result. Example 2: Filtering Groups by SumHere we will find products with a total quantity sold greater than 10: SELECT product, SUM(quantity) Output: +---------+---------------+ Explanation: Total quantity of mouse sold is 10 + 6 + 6 = 22, which is greater than 10. Other products (e.g., Laptop, Keyboard, Headphones) have total quantities that do not exceed 10, so they are excluded from the result. ConclusionThe HAVING clause in MySQL is great for filtering grouped data after using the GROUP BY clause. This help us to get more specific results from data. We’ve covered the basics and provided some simple examples to help you understand how to use the HAVING clause in your own queries. FAQ’s on MySQL HAVING ClauseHow is HAVING different from WHERE?
Can I use HAVING without GROUP BY?
Can I use multiple conditions in HAVING?
Can I use HAVING with subqueries?
|
Reffered: https://www.geeksforgeeks.org
Databases |
Related |
---|
![]() |
![]() |
![]() |
![]() |
![]() |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 30 |