Welcome to the Treehouse Community
Looking to learn something new?
Jeff Styles2,784 Points
Using LENGTH function as a condition without issuing an alias or displaying its value in output...
As the LENGTH function and HAVING clause are explained in this lesson, the following statement will display all usernames associated with a person who's first name is less than 4 characters:
SELECT username, LENGTH(first_name) as first_name_length FROM users HAVING first_name_length < 4;
OUTPUT: username: Bendog24 first_name_length: 3
But, if I wanted to just display the usernames in output, and not the length data, I wouldn't need an alias and would run the following statement:
SELECT username FROM users HAVING LENGTH(first_name) < 4;
OUTPUT: error code 1054 unknown column 'first_name' in 'having clause'
However. if I run the same statement with a WHERE clause instead of HAVING, it outputs just what I intend it to:
SELECT username FROM users WHERE LENGTH(first_name) < 4;
OUTPUT: username: Bendog24
I'm confused by this. Why does HAVING clause work only when data from the LENGTH function is selected and aliased for output? And is it ok to use WHERE with LENGTH since it seems to work?