Course
Having Clause
MySQL Tutorial
This SQL tutorial is structured for beginners to guide them from the foundational concepts to advanced data manipulation and querying techniques in SQL. By the end of this tutorial, you will have developed a robust understanding of SQL, equipping you with the knowledge to efficiently manage and analyze data across various database systems. This guide sets the stage for your growth into a skilled data professional, ready to tackle complex data challenges and contribute to the field of data analysis and database management.
Having Clause
MySQL Having Clause
The MySQL HAVING Clause is used to filter grouped rows in a table based on conditions.
This clause is used with the GROUP BY clause to group the rows based on one or more columns and then filter them based on the conditions specified in the HAVING clause. So, the HAVING clause must always be followed by the GROUP BY clause.
The HAVING clause was added to MySQL because the WHERE keyword cannot be used with aggregate functions such as COUNT(), SUM(), AVG(), etc.
This clause is similar to the MySQL WHERE clause. The difference between both of them is that the WHERE clause filters individual rows in a table, whereas the HAVING clause filters grouped rows based on conditions.
Syntax
Following is the basic syntax of the HAVING clause in MySQL
SELECT column1, column2, aggregate_function(column)FROM table_nameGROUP BY column1, column2, ...HAVING conditionORDER BY column1, column2, ...;
Example
Let us begin with creating a table named CUSTOMERS using the following query
CREATE TABLE CUSTOMERS ( ID INT NOT NULL, NAME VARCHAR (20) NOT NULL, AGE INT NOT NULL, ADDRESS CHAR (25), SALARY DECIMAL (18, 2), PRIMARY KEY (ID));
The following INSERT statement inserts 7 records into the above-created table
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 ),(2, 'Khilan', 25, 'Delhi', 1500.00 ),(3, 'Kaushik', 23, 'Kota', 2000.00 ),(4, 'Chaitali', 25, 'Mumbai', 6500.00 ),(5, 'Hardik', 27, 'Bhopal', 8500.00 ),(6, 'Komal', 22, 'Hyderabad', 4500.00 ),(7, 'Muffy', 24, 'Indore', 10000.00 );
Using the following query, we can verify whether the CUSTOMERS table is created or not
SELECT * FROM CUSTOMERS;
Following is the CUSTOMERS table
HAVING clause with ORDER BY clause
In MySQL, the HAVING clause filters the groups, and the ORDER BY clause sorts the results. When we used both of them together, HAVING is executed first, then the result set is sorted according to the ORDER BY criteria.
Example
In the following query, we are retrieving all the records from the CUSTOMERS table where the sum of their SALARY is less than 4540, ordered by their name in ascending order
SELECT NAME, SUM(SALARY) as total_salaryFROM CUSTOMERSGROUP BY NAMEHAVING SUM(SALARY) < 4540ORDER BY NAME;
Output
The output for the query above is produced as given below
HAVING clause with COUNT() function
We can use the MySQL HAVING clause in conjunction with the COUNT() function to filter the groups based on the number of rows they contain.
Example
In this query, we are fetching a record where the count of similar age is greater than or equal to 2.
SELECT AGEFROM CUSTOMERSGROUP BY ageHAVING COUNT(age) >= 2;
Output
There are two records in CUSTOMERS table with age 25, thus the output is 25
HAVING clause with AVG() function
The MySQL HAVING clause can also be used with the AVG() function to filter groups based on the average value of a specified column.
Example
In the following query, we are trying to return the names of the customers whose salary is greater than 3000
SELECT NAME, AVG(salary) as avg_salaryFROM customersGROUP BY NAMEHAVING AVG(salary) > 3000;
Output
The output for the query above is produced as given below
HAVING clause with MAX() function
In MySQL, we can also use the HAVING clause with MAX() function to filter groups based on the maximum value of a specified column.
Example
In this query, we are retrieving the customer names whose maximum SALARY is less than 4000
SELECT NAME, MAX(salary) as max_salaryFROM customersGROUP BY NAMEHAVING MAX(salary) < 4000;
Output
On executing the given query, the output is displayed as follows
Having Clause Using a Client Program
Besides using MySQL HAVING clause to filter grouped rows in a table based on conditions, we can also use client programs like Node.js, PHP, Java, and Python to achieve the same result.
Syntax
Following are the syntaxes of this operation in various programming languages
PHPNodeJSJavaPython
To filter grouped rows in a table based on conditions through PHP program, we need to execute SELECT statement with HAVING clause using the mysqli function query() as follows
$sql = "SELECT EXPRESSION1, EXPRESSION2, ...EXPRESSION_N, AGGREGATE_FUNCTION(EXPRESSION) FROM TABLE_NAME [WHERE CONDITION] GROUP BY EXPRESSION1, EXPRESSION2.. EXPRESSION_N HAVING CONDITION";$mysqli->query($sql);
Example
Following are the programs
PHPNodeJSJavaPython
$dbhost = 'localhost';$dbuser = 'root';$dbpass = 'password';$dbname = 'TUTORIALS';$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);if($mysqli->connect_errno ) { printf("Connect failed: %s", $mysqli->connect_error); exit();}//printf('Connected successfully.');$sql = 'SELECT tutorial_title, count(tutorial_id) AS tot_count FROM tutorials_tbl WHERE tutorial_id > 1 GROUP BY tutorial_title HAVING count(tutorial_id) > 1';$result = $mysqli->query($sql);if ($result->num_rows > 0) { printf("Table records: \n"); while($row = $result->fetch_assoc()) { printf("Title: %s, Count: %d", $row["tutorial_title"], $row["tot_count"]); printf("\n"); }} else { printf('No record found.');}mysqli_free_result($result);$mysqli->close();
Output
The output obtained is as follows
Table records:Title: Learn MySQL, Count: 2