Home >Database >Mysql Tutorial >Why Does 'select* from staff where salary > avg(salary)' Return 'ERROR 1111 (HY000): Invalid Use of Group Function'?
avg(salary)" Return "ERROR 1111 (HY000): Invalid Use of Group Function"? " /> avg(salary)" Return "ERROR 1111 (HY000): Invalid Use of Group Function"? " />
An attempt to list staff earning above the average salary using the query "select* from staff where salary > avg(salary)" returns the "ERROR 1111 (HY000): Invalid use of group function." This issue arises due to incorrect usage of an aggregate function in the WHERE clause.
An aggregate function, such as AVG() in this case, cannot be used in the WHERE clause unless specific conditions are met. According to the SQL standards, aggregates can appear in the WHERE clause if they are used in a subquery with a HAVING clause or a select list, and the aggregated column is an outer reference.
To address the error, rewrite the query using a subquery in the WHERE clause:
select * from staff where salary > (select avg(salary) from staff)
This query uses a subquery to calculate the average salary, which is then compared to the salary of each staff member.
Alternatively, consider using the HAVING clause to filter the aggregate data:
select deptid,COUNT(*) as TotalCount from staff group by deptid having count(*) > 2
The HAVING clause in this query restricts the results to departments with more than two staff members.
The above is the detailed content of Why Does 'select* from staff where salary > avg(salary)' Return 'ERROR 1111 (HY000): Invalid Use of Group Function'?. For more information, please follow other related articles on the PHP Chinese website!