Question

I have a simple MySQL select and I want to order by Company Name and First Name. The columns of the table are:

COMPANY_NAME

FIRST_NAME

LAST_NAME

When I run a select with a standard ORDER BY, I get the following:

SELECT COMPANY_NAME, FIRST_NAME, LAST_NAME
from TABLE_contacts
WHERE CONTACT_STATUS = 'ACTIVE'
ORDER BY COMPANY_NAME, FIRST_NAME;

+------------------+------------+-----------+
| COMPANY_NAME     | FIRST_NAME | LAST_NAME |
+------------------+------------+-----------+
|                  | Bob        | Jones     |
|                  | Mark       | Doe       |
| Acme Company     | Joan       | Todd      |
| Fun Company      |            |           |
+------------------+------------+-----------+

However, I need the list to be in alphabetical order. There are cases when company name will be empty or first name will be empty. My goal would be to list in alphabetical order using the company name if it exists and first name if it does not for an output like this:

+------------------+------------+-----------+
| COMPANY_NAME     | FIRST_NAME | LAST_NAME |
+------------------+------------+-----------+
| Acme Company     | Joan       | Todd      |
|                  | Bob        | Jones     |
| Fun Company      |            |           |
|                  | Mark       | Doe       |
+------------------+------------+-----------+

I've tried the statement below but my results are the same:

SELECT COMPANY_NAME, FIRST_NAME, LAST_NAME
from TABLE_contacts
WHERE CONTACT_STATUS='ACTIVE'
ORDER BY CASE WHEN COMPANY_NAME IS NULL THEN FIRST_NAME ELSE COMPANY_NAME END DESC;

Thank you for any help!

Was it helpful?

Solution

I think you want:

order by coalesce(Company_Name, First_Name)

However, this is assuming that Company_Name is NULL and not blank. You might need an extension of your logic:

order by (case when Company_Name is not null and Company_Name <> ''
               then Company_Name
               else First_Name
          end)

I'm not sure what the desc is for in your example. Your desired results are in ascending order.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top