I\'m using mySQL. I have to order names of Contacts by Lastname but in the case that there is no last name, I order by firstname.
This looks like:
OR
ORDER BY
CASE
WHEN LName is null
THEN FName
ELSE LName
END
more here
Try using Coalesce
Note: this would require you not to store empty last names using an empty string (ie "")
ORDER BY Coalesce(LastName, FirstName)
As Suggested in the Comments By adding FirstName to the order By list again you will properly order two people with the same lastName. Here is an example.
ORDER BY Coalesce(LastName, FirstName), FirstName
ORDER BY
supports custom sorting. But given your logic, I would suggest creating a field in your SELECT
with CONCAT
and then ordering on it.
SELECT *, IF(LENGTH(lastname) = 0, firstname, CONCAT(lastname, ', ', firstname)) AS fullname
FROM contacts
ORDER BY fullname;
This also has the benefit of returning fullname
in your results based on your same sorting logic.
Use COALESCE and NULLIF:
ORDER BY COALESCE(NULLIF(LastName, ''), FirstName), FirstName