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

Kane Stoboi
Kane Stoboi
21,919 Points

MySQL order by multiple columns

I have a MySQL table like the one below with more information in cells to the right. each row has either a last name or an organisation name.

| lastName | organisationName |

| Smith-----|------------------------|

|-------------| Treehouse ---------|

| Greg------|------------------------|

|-------------| Ally's ----------------|

what I want to do is select everything from the table and order each row by the last name and organisation name so that is is displayed like this.

  • Ally's
  • Greg
  • Smith
  • Treehouse

I've been using SELECT * FROM table_name ORDER BY

but I'm struggling with what to order it by.

2 Answers

Yousuf Tafhim
Yousuf Tafhim
8,402 Points

The answer would be to do a query in a way that both the columns are merged into a single column and then that column is sorted. Something like

SELECT (lastName || '  '|| organizationName) FROM table_name

OR

SELECT CONCAT(lastName," ",organizationName) FROM table_name
Khaleel Hamid
Khaleel Hamid
5,258 Points

Perhaps try this

SELECT * FROM table_name 
ORDER BY lastName, organizationName

This orders by last name first and then organization name.

However it'll output like this

| lastName | organizationName |

| Greg-----|------------------------|

|-------------| Ally's ---------|

| Smith------|------------------------|

|-------------| Treehouse ----------------|

Kane Stoboi
Kane Stoboi
21,919 Points

Thanks Khaleel, I've explored using that method however I need the data displayed like I mention above

Khaleel Hamid
Khaleel Hamid
5,258 Points

The only way I can see the data being displayed like that if it were in the same column. Unless someone else knows a how to display like that without it.