MySQL Select request error

Started by Optimitron, Dec 29, 2022, 05:38 AM

Previous topic - Next topic

OptimitronTopic starter

Good afternoon. There seems to be an issue with my query where all data is stored in one User table. The first query returns the expected result, but the second query results in an error. Can you help me identify what I am doing wrong?

select registration_type, count(1) from user where is_active=1 and registration_time > '2019-01-01' group by registration_type order by 2 desc limit 2;
It appears that the column 'registration_time' is unknown in the having clause which leads to this error [ERROR 1054 (42S22)]. Can you check if this column exists and is correct in your database?


When using the Having clause, it is required to "substitute" an aggregate function or a grouping condition. It is not possible to use columns that are not part of an aggregate function or grouping condition in the Having clause. This is because the Having clause filters data after grouping and aggregation has taken place.

SELECT registration_type, COUNT(1)
WHERE is_active=1
GROUP BY registration_type
HAVING registration_TYPE =,<,> Here is the grouping value from GROUP BY

It is important to understand the difference between the Where and Having clauses in SQL. While the Where clause filters data before grouping and aggregation, the Having clause filters data after. Additionally, the Having clause can only be used in conjunction with the Group By clause, which specifies the grouping condition.


based on the error message you provided, it seems that the column 'registration_time' is not recognized in the HAVING clause.

To troubleshoot this issue, you may want to check if the column 'registration_time' exists in your 'user' table and if it is spelled correctly. Additionally, make sure that the alias 'registration_type' is correct and is associated with a valid column in your table.

If the column does exist and the alias is correct, you might consider modifying your query to ensure that the HAVING clause refers to a valid column and meets the conditions you desire.

Upon reviewing your query again, I noticed that the issue lies in the use of the HAVING clause with the column 'registration_time'.

The HAVING clause is typically used to filter results based on aggregate functions, such as SUM or COUNT, and not individual columns. In your case, it seems like you want to filter the rows based on the 'registration_time' column, which should be done in the WHERE clause instead.

You can modify your query as follows:

SELECT registration_type, COUNT(1)
FROM user
WHERE is_active = 1 AND registration_time > '2019-01-01'
GROUP BY registration_type

By moving the condition `registration_time > '2019-01-01'` from the HAVING clause to the WHERE clause, you should be able to execute the query without encountering the "unknown column" error.