Resolve Error 1111: Invalid Use of Group Function in MySQL



To correctly use aggregate function with where clause in MySQL, the following is the syntax −

select *from yourTableName
where yourColumnName > (select AVG(yourColumnName) from yourTableName);

To understand the above concept, let us create a table. The query to create a table is as follows −

mysql> create table EmployeeInformation
   -> (
   -> EmployeeId int,
   -> EmployeeName varchar(20),
   -> EmployeeSalary int,
   -> EmployeeDateOfBirth datetime
   -> );
Query OK, 0 rows affected (1.08 sec)

Now you can insert some records in the table using insert command. The query is as follows −

mysql> insert into EmployeeInformation values(101,'John',5510,'1995-01-21');
Query OK, 1 row affected (0.13 sec)
mysql> insert into EmployeeInformation values(102,'Carol',5600,'1992-03-25');
Query OK, 1 row affected (0.56 sec)
mysql> insert into EmployeeInformation values(103,'Mike',5680,'1991-12-25');
Query OK, 1 row affected (0.14 sec)
mysql> insert into EmployeeInformation values(104,'David',6000,'1991-12-25');
Query OK, 1 row affected (0.23 sec)
mysql> insert into EmployeeInformation values(105,'Bob',7500,'1993-11-26');
Query OK, 1 row affected (0.16 sec)

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

mysql> select *from EmployeeInformation;

The following is the output −

+------------+--------------+----------------+---------------------+
| EmployeeId | EmployeeName | EmployeeSalary | EmployeeDateOfBirth |
+------------+--------------+----------------+---------------------+
|        101 | John         |           5510 | 1995-01-21 00:00:00 |
|        102 | Carol        |           5600 | 1992-03-25 00:00:00 |
|        103 | Mike         |           5680 | 1991-12-25 00:00:00 |
|        104 | David        |           6000 | 1991-12-25 00:00:00 |
|        105 | Bob          |           7500 | 1993-11-26 00:00:00 |
+------------+--------------+----------------+---------------------+
5 rows in set (0.00 sec)

Here is the correct way to use aggregate with where clause. The query is as follows −

mysql> select *from EmployeeInformation
   -> where EmployeeSalary > (select AVG(EmployeeSalary) from EmployeeInformation);

The following is the output −

+------------+--------------+----------------+---------------------+
| EmployeeId | EmployeeName | EmployeeSalary | EmployeeDateOfBirth |
+------------+--------------+----------------+---------------------+
|        105 | Bob          |           7500 | 1993-11-26 00:00:00 |
+------------+--------------+----------------+---------------------+
1 row in set (0.04 sec)
Updated on: 2019-07-30T22:30:25+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements