0

I am getting an error saying that the total_calories in the HAVING clause is not a valid column:

SELECT type, SUM(calories) AS total_calories FROM exercise_logs
GROUP BY type
HAVING total_calories > 150;

Any ideas why this is happening? Thank you.

Stackedup
  • 680
  • 2
  • 9
  • 26
  • Possible duplicate of [SQL HAVING SUM GROUP BY](https://stackoverflow.com/questions/2088727/sql-having-sum-group-by) – Ed Bangga Sep 04 '19 at 00:46

1 Answers1

1

You need to use your aggregate column. Alias can only be used in order by or subquery

SELECT type, SUM(calories) AS total_calories FROM exercise_logs
GROUP BY type
HAVING SUM(calories) > 150;
Avi
  • 1,795
  • 3
  • 16
  • 29
  • 1
    . . That actually depends on the database. Many databases actually do support aliases in the `HAVING` clause. – Gordon Linoff Sep 04 '19 at 12:02
  • @GordonLinoff Thank You for providing information ! I did not know that I was basing this based on SQL server.. – Avi Sep 04 '19 at 22:40