Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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?

Thanks!