Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error Code 1111. Invalid use of group function

So this works:

SELECT c.name AS country_name, c.population AS country_population, SUM(ci.population) AS city_population, ROUND(100*(SUM(ci.population)/c.population)) AS city_population_percent
FROM country AS c
JOIN city AS ci
ON c.code = ci.countrycode
WHERE c.continent = 'Europe'
GROUP BY c.name

But I need to only grab the city_population_percent values greater than 30, so I try this:

SELECT c.name AS country_name, c.population AS country_population, SUM(ci.population) AS city_population, ROUND(100*(SUM(ci.population)/c.population)) AS city_population_percent
FROM country AS c
JOIN city AS ci
ON c.code = ci.countrycode
WHERE c.continent = 'Europe'
**AND ROUND(100*(SUM(ci.population)/c.population)) > 30**
GROUP BY c.name

And that's when I get:

Error Code 1111. Invalid use of group function

That is, it fails when I add this condition in the WHERE:

AND ROUND(100*(SUM(ci.population)/c.population)) > 30
like image 275
user3374108 Avatar asked Mar 03 '14 08:03

user3374108


People also ask

What is invalid use of group function 1111?

The MySQL error Invalid use of group function is caused by aggregate functions in your query that's placed in the wrong clause. Most likely you are placing one or more aggregate functions inside the WHERE clause, which won't work because the WHERE clause filters the table before MySQL actually does the computation.

What does Error Code 1111 mean?

Error code 1111: says invalid use of group function.

What is group by in MySQL?

The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country". The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.

How do I fix error 1054 in MySQL?

To fix the error above, simply add a quotation mark around the value. You can use both single quotes or double quotes as shown below: INSERT INTO users(username, display_name) VALUES ("jackolantern", 'Jack'); Now the INSERT statement should run without any error.


2 Answers

So you have to move this condition to the HAVING clause

SELECT c.name AS country_name, c.population AS country_population, SUM(ci.population) AS city_population, ROUND(100*(SUM(ci.population)/c.population)) AS city_population_percent
            FROM country AS c
            JOIN city AS ci
            ON c.code = ci.countrycode
WHERE c.continent = 'Europe'
GROUP BY c.name
HAVING ROUND(100*(SUM(ci.population)/c.population)) > 30
like image 116
Surabhil Sergy Avatar answered Sep 21 '22 16:09

Surabhil Sergy


You're using aggregate functions in a where clause, something you cannot do in SQL.

Use the HAVING clause instead:

WHERE c.continent = 'Europe'
GROUP BY c.name
HAVING ROUND(100*(SUM(ci.population)/c.population)) > 30
like image 35
nos Avatar answered Sep 23 '22 16:09

nos