Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Column does not exist error when using Having clause

I’m following along the steps in this article and am having trouble with the following query:

SELECT Quantity, COUNT(*) AS Quantity_Counts
FROM sqlbank3
WHERE UnitPrice >= 5
GROUP BY Quantity
HAVING Quantity_Counts < 450
ORDER BY Quantity_Counts DESC
LIMIT 10;

ERROR: column "quantity_counts" does not exist

LINE 5: HAVING Quantity_Counts < 450

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I put everything in lower case to see if that did anything but to no avail. I have created Quantity as an integer. The query runs when I remove the HAVING clause so it’s certainly finding the Quantity_Counts column, just not with the HAVING clause.
Any help is appreciated.

>Solution :

The HAVING clause is supposed to be evaluated before the SELECT clause. You cannot use the alias defined in SELECT in HAVING for that reason.

You must use

HAVING COUNT(*) < 450

instead.

(Some DBMS allow it to use alias names in the HAVINGclause, though.)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading