HAVING with GROUP BY in MySQL


To use HAVING with GROUPBY in MySQL, the following is the syntax. Here, we have set a condition under HAVING to get check for maximum value condition −

SELECT yourColumnName FROM yourTableName GROUP BY yourColumnName HAVING MAX(yourColumnName) < yourValue;

Let us see an example by creating a table in MySQL −

mysql> create table WhereAfterGroupDemo
-> (
-> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> UserProcess int,
-> UserThreadId int
-> );
Query OK, 0 rows affected (5.74 sec)

Example

Insert some records in the table using insert command. The query is as follows −

mysql> insert into WhereAfterGroupDemo(UserProcess,UserThreadId) values(1211,3);
Query OK, 1 row affected (0.10 sec)
mysql> insert into WhereAfterGroupDemo(UserProcess,UserThreadId) values(1412,3);
Query OK, 1 row affected (0.39 sec)
mysql> insert into WhereAfterGroupDemo(UserProcess,UserThreadId) values(1510,4);
Query OK, 1 row affected (0.19 sec)
mysql> insert into WhereAfterGroupDemo(UserProcess,UserThreadId) values(1511,4);
Query OK, 1 row affected (0.31 sec)

Display all records from the table using a select statement. The query is as follows −

mysql> select *from WhereAfterGroupDemo;

Output

+--------+-------------+--------------+
| UserId | UserProcess | UserThreadId |
+--------+-------------+--------------+
|      1 | 1211        |            3 |
|      2 | 1412        |            3 |
|      3 | 1510        |            4 |
|      4 | 1511        |            4 |
+--------+-------------+--------------+
4 rows in set (0.00 sec)

The following is the query to use HAVING and GROUP BY and get the UserThreaId with process less than 1510 −

mysql> SELECT UserThreadId FROM WhereAfterGroupDemo GROUP BY UserThreadId HAVING MAX(UserProcess) < 1510;

Output

+--------------+
| UserThreadId |
+--------------+
|            3 |
+--------------+
1 row in set (0.00 sec)

Updated on: 06-Mar-2020

308 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements