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:
ORDER BY lastname = "", lastname, firstname
However, this makes the ones with lastnames appear at the top. The behaviour I'd like is to intermix the first and lastnames like they were from the same field.
Example (pretend these are names):
A,T
Z,G
A
B
C
Versus:
A
A,T
B
C
Z,G
Thanks
Use COALESCE and NULLIF:
ORDER BY COALESCE(NULLIF(LastName, ''), FirstName), FirstName
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With