SQL sorting when sort field is null
May 2, 2008 7:09 PM
Subscribe
MySQL sorting issue. When I have "first name" and "last name" columns, and I'm sorting primarily by "last name." Some entries have only a "first name," and rather than have those end up at either the start or end of the sort, I'd like it to pretend the "first name" IS the "last name" and sort accordingly. Is there a way to do this with the SQL SELECT statement or should I just edit the data?
So, I've got this list of names like:
Ron
Bill Smith
Adam Jones
Steve Washington
They're split up into "firstName" "lastName" fields. For purposes of the webpage they're getting displayed on, I'm concatenating them into a single "fullName" field, and will be sorting "ORDER BY lastName." Except a few names only have "firstName." Left alone, MySQL seems to put those at the beginning of the list, and I've seen some info on ways to push them to the bottom - but what I want, is when "lastName is null" to have it use "firstName" instead, so that the list above would end up:
Adam Jones
Ron
Bill Smith
Steve Washington
I realize one option would be to just edit the data and wherever there's a first name only to move that into the "last name" field (because once concatenated the displayed name will be the same) but that just seems like a bad solution in the long term, if there's a way to make the SQL do this for me.
(I'm pretty new to MySQL so forgive me if there's some obvious answer. I've searched forums via Google but I can't find questions quite like this.)
posted by dnash to computers & internet (8 comments total)
1 user marked this as a favorite
ORDER BY my_name ASC;
posted by SPrintF at 7:31 PM on May 2