The HAVING Clause

Hi Codecademy,

In SQL, we can use numbers 1, 2, 3… etc in order to reference the columns that we are SELECTing so that we dont have to retype them all of the time.

I originally had this code:

Note that ‘1’ is supposed to reference user_id
and ‘2’ was supposed to reference SUM(watch_duration_in_minutes) AS ‘Total Minutes’

SELECT user_id, SUM(watch_duration_in_minutes) AS ‘Total Minutes’
FROM watch_history
GROUP BY 1
HAVING 2 > 400;

Well that did not work… I had to change the ‘2’ to ‘Total Minutes’ in order for it to work:

SELECT user_id, SUM(watch_duration_in_minutes) AS ‘Total_Minutes’
FROM watch_history
GROUP BY 1
HAVING Total_Minutes > 400;

Why?

One more question: Total_Minutes has to have the “_” to connect the words. So I guess I cannot use ‘Total Minutes’

Thanks

Eric

When you use 2 > 400, SQL is unable to clarify that the ’ 2 ’ is a numeric value of the reference SUM(watch_duration_in_minutes) so it returns an error. It’s best to use an alias name in to replace the second command which is much shorter! AND it’s best to use an underscore to declare an alias name which improves readability though even omitted it still works!