Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Development Tools Database Foundations SQL Calculating, Aggregating and Other Functions String Functions

Jeff Styles
Jeff Styles
2,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?