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 Clause
The HAVING
clause allows you to apply conditions to the groups created by the GROUP BY
clause. It is particularly useful when you want to filter data based on aggregate values such as sums, averages, counts, etc. Essentially, it works like a WHERE
clause but is used with grouped data.
Syntax:
SELECT column1, column2, AGGREGATE_FUNCTION(column_name)
FROM table_name
GROUP BY column1, column2
HAVING AGGREGATE_FUNCTION(column_name) condition;
Where:
column1, column2
: Columns to include in the result.table_name
: The table from which to retrieve data.AGGREGATE_FUNCTION(column_name)
: An aggregate function applied to a column.condition
: The condition to filter the aggregated results.
Demo MySQL Database
To 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 (
id INT AUTO_INCREMENT PRIMARY KEY,
product VARCHAR(50),
quantity INT,
price DECIMAL(10, 2)
);
INSERT INTO sales (product, quantity, price) VALUES
('Laptop', 2, 1000),
('Mouse', 10, 20),
('Laptop', 3, 1000),
('Mouse', 6, 20),
('Keyboard', 5, 50),
('Headphones', 5, 800),
('Mouse', 6, 20);
Output:
OutputExamples of MySQL HAVING Clause
Example 1: Filtering Groups by Count
In this example we will the find products that have been sold more than once.
SELECT product, COUNT(*)
FROM sales
GROUP BY product
HAVING COUNT(*) > 1;
Output:
+---------+----------+
| product | COUNT(*) |
+---------+----------+
| Laptop | 2 |
| Mouse | 3 |
+---------+----------+
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 Sum
Here we will find products with a total quantity sold greater than 10:
SELECT product, SUM(quantity)
FROM sales
GROUP BY product
HAVING SUM(quantity) > 10;
Output:
+---------+---------------+
| product | SUM(quantity) |
+---------+---------------+
| Mouse | 22 |
+---------+---------------+
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.
Conclusion
The 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.
Similar Reads
SQLite HAVING Clause
SQLite is a server-less database engine and it is written in c programming language. The main moto for developing SQLite is to escape from using complex database engines like MySQL etc. It has become one of the most popular database engines as we use it in Television, Mobile Phones, web browsers, an
5 min read
PL/SQL HAVING Clause
The PL/SQL HAVING clause is a powerful tool used in SQL for filtering records in groups defined by the GROUP BY clause. While the WHERE clause filters individual rows, the HAVING clause filters groups based on aggregate functions like SUM, COUNT, MIN, and MAX. This clause is essential when we want t
5 min read
PostgreSQL - HAVING clause
The HAVING clause in PostgreSQL is an essential feature for filtering grouped data that has been aggregated using functions like SUM(), COUNT(), AVG(), and others. Unlike the WHERE clause, which filters rows before aggregation, the HAVING clause is used to filter results after the grouping and aggre
4 min read
MySQL LIMIT Clause
MySQL consists of various clauses for performing efficient data retrieval, and the LIMIT clause is essential for controlling the number of rows returned in a query. By specifying a limit on the number of results, the LIMIT clause helps manage large datasets, optimize performance, and focus on releva
4 min read
MariaDB Having Clause
The HAVING clause is crucial for filtering and aggregating data in database queries. The MariaDB HAVING clause syntax is outlined. It breaks down into components. These include the SELECT clause, aggregate functions, and the GROUP BY clause. The SELECT clause specifies columns. Aggregate functions p
6 min read
MySQL DISTINCT Clause
When working with databases, you often need to filter out duplicate records to get a clear and accurate result set. MySQL offers a straightforward solution for this with the DISTINCT clause. This clause helps you retrieve only unique rows from your query results, making it an essential tool for data
4 min read
Having vs Where Clause in SQL
In SQL, filtering data is important for extracting meaningful insights from large datasets. While both the WHERE and HAVING clauses allow us to filter data, they serve distinct purposes and operate at different stages of the query execution process. Understanding the difference between these clauses
4 min read
MySQL Group By Clause
In MySQL, the GROUP BY clause is a powerful tool for grouping rows with the same values into summary rows, enabling efficient data analysis. It is often used with aggregate functions like SUM, COUNT, AVG, MIN, and MAX to perform calculations on grouped data. In this article, We will learn about the
4 min read
SQL HAVING Clause with Examples
The HAVING clause in SQL is used to filter query results based on aggregate functions. Unlike the WHERE clause, which filters individual rows before grouping, the HAVING clause filters groups of data after aggregation. It is commonly used with functions like SUM(), AVG(), COUNT(), MAX(), and MIN().
4 min read
SQL Distinct Clause
The SQL DISTINCT keyword is used in queries to retrieve unique values from a database. It helps in eliminating duplicate records from the result set. It ensures that only unique entries are fetched. Whether you're analyzing datasets or performing data cleaning, the DISTINCT keyword is Important for
4 min read