Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: ORDER BY two columns intermixed, not priority based

Tags:

sql

mysql

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

like image 830
Tyler Avatar asked Dec 22 '10 19:12

Tyler


2 Answers

Use COALESCE and NULLIF:

ORDER BY COALESCE(NULLIF(LastName, ''), FirstName), FirstName
like image 108
Cade Roux Avatar answered Sep 17 '22 18:09

Cade Roux


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
like image 22
John Hartsock Avatar answered Sep 19 '22 18:09

John Hartsock