Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL - Sort 2 Columns Alphabetically, using second column if first column is null

Tags:

sorting

mysql

I am trying to sort my mysql database referencing two columns alphabetically where company_name is the primary sort but if there is no company_name then sort by last_name. I will list an example below.

company_name: (primary sort column)
1 ABC Trucking
2 Genius Heating
3
4 Xtreme Windows

last_name: (secondary column)
1 Bryant
2 Rogers
3 Flint
4 Lewis

Sorts like this:
1 ABC Trucking
3 Flint
2 Genius Heating
4 Xtreme Windows

Is this even possible or should i just merge these into an array and sort them using php?

like image 202
Lawrence Gadette Avatar asked Jan 25 '12 18:01

Lawrence Gadette


1 Answers

Just make select with a column as 'name' using a case and order by it. Best shown by example.

SELECT
CASE WHEN company_name IS NULL THEN last_name ELSE company_name END AS name
FROM mytable
ORDER BY name ASC

If you really wanted to, you can also used the case statement right in the order by clause.
I think the above is really a better solution to your problem because you no longer even have the logic in the php, but you may disagree.

SELECT company_name, last_name
FROM mytable
ORDER BY CASE WHEN company_name IS NULL THEN last_name ELSE company_name END ASC

EDIT: I only assumed company_name IS NULL is correct for you case. If you need to do this on a different condition then thats you're own exercise. Is it null? or should be comparing it to '' instead?

like image 126
user606723 Avatar answered Nov 15 '22 00:11

user606723