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
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.
CodePudding user response:
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 HAVING
clause, though.)