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

Databases

Longest Name

For the first practice query in playground, is there a way to order by an alias name? If I give LENGTH(name) an alias such as 'Name Length', is there a way I can order by 'Name Length' or would I have to order by LENGTH(name)?

1 Answer

Steven Parker
Steven Parker
230,274 Points

Either should work.

You should be able to ORDER BY the alias just as easily as by the term that produces the column.

The following query: SELECT name, LENGTH(name) AS 'Name Length' FROM actors ORDER BY 'Name Length' DESC LIMIT 1; returns name: 'Chico' Hernandez, Name Length: 17

But this one: SELECT name, LENGTH(name) AS 'Name Length' FROM actors ORDER BY LENGTH(name) DESC LIMIT 1; returns name: The Hallelujah Singers of Beaufort South Carolina, Name Length: 49

And if I don't have Name Length in quotes I get this error - Error: near "Length": syntax error

Steven Parker
Steven Parker
230,274 Points

Yes, any name that has spaces in it must be enclosed in quotes.

As for the deviation in the results, can you provide a link to a course page where I could try your examples in the playground or challenge?

Steven Parker
Steven Parker
230,274 Points

Ahh. That was the wrong kind of quote for a column name. What you need there is:

SELECT name, LENGTH(name) AS "Name Length" FROM actors ORDER BY "Name Length" DESC LIMIT 1;

Remember: single quotes (') are for strings, double quotes (") are for column names.